Search code examples
cfunctionpointersmemory-managementpointer-to-pointer

Do I need a pointer to a pointer here?


I have the following code:

char* get_line(char *buffer, char *line, char *partialLine) {

  int i = 0;
  while (buffer[i] != '\n' && buffer[i] != '\0') i++;

  if (buffer[i] == '\n') {

    line = malloc(sizeof(char) * (i+2));
    memcpy(line,buffer,i+1);
    line[i+1] = '\0';

    char *temp = append(partialLine,line);
    if (partialLine) {
      free(partialLine);
      partialLine = NULL;
    }
    free(line);
    line = temp;
    buffer = pop_buffer(buffer,i+1);

    return buffer;
  }
}

I want the function to fill in "line", so that when I return I have the value of temp in "line". At the moment, when debugging I see line gets the right value after the line = temp instruction. I want this to be kept after the return.

I think I need to pass a pointer to a pointer making the function prototype char* get_line(char *buf, char **line, char *partialLine);, but I'm only just getting to grips with regular pointers. What is the best way to solve this type of problem? Am I on the right tracks?


Solution

  • You already give the better part of the answer. Just one nitpick:

    At the moment, when debugging I see line gets the right value after the line = temp instruction. I want this to be kept after the return.

    That's impossible. C function calls pass arguments by value, so the line inside the function is a different variable than that outside and doesn't exist any more once the function exits. That's why you need to pass a pointer to a pointer here.

    The bit of information you seem to be missing: A pointer isn't that much different from a normal variable, it stores a value. The only difference is that the value stored is the address of some other variable. Of course, you can handle a pointer to a pointer just the same way as a pointer to anything, and you can dereference twice. In your case, the simplest way would be to just change the parameter type and then replace every line by *line (which would access the pointer line points to).