tags:

views:

274

answers:

4

I need to pass in a char * in a function and have it set to a cstring value. I can properly set it as a string in the function, but it doesn't seem to print out correctly in the function that called the char * function in the first place.

int l2_read(char *chunk,int length)
{
    chunk = malloc( sizeof(char) * length);

    int i;
    for(i = 0; i < length; i++){
       char c;
       if(read(&c) < 0) return (-1); // this gets a single character
          chunk[i] = c;
    }

    printf("%s",chunk); // this prints fine
    return 1;
}


    // main
    char *string;
    int value = l2_read(string,16);
    printf("%s",chunk); // prints wrong
+2  A: 

I just re-read your question.

You seem to have been hit by the pass by value, even if it is a pointer, problem. Also, is chunk null terminated?

Moron
+4  A: 
Alok
+2  A: 

You have to pass a pointer to a pointer.

int l2_read(char **chunk,int length)
{
    *chunk = malloc( sizeof(char) * length);

     int i;
     for(i = 0; i < length; i++)
     {
         char c;
         if (read(&c) < 0) return (-1);
         (*chunk)[i] = c;
     }

     printf("%s",*chunk);
     return 1;

}

    char *string;
    int value = l2_read(&string,16);
    printf("%s",string);
A: 

I totally agree with the answer posted above. You are essentially modifying the value of pointer so you need to pass the reference of pointer. use char ** instead of char*.

Himanshu