Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the &-operand when passing a pointer to a function?

int enter_path(char** path) {
  char* standard = "./questions.txt";
   printf("\n\t%s\n\t%s",
          "Please enter the file location.", "path: ");
   fgets(*path, MAX_PATH_LENGTH ,stdin);
     *(*path + (strlen(*path)-1) ) = '\0';
   if(**path == '\n' )
     *path = strdup(standard);
   return 0;
}

int main(void){
  char* path = malloc(MAX_PATH_LENGTH);
  enter_path(&path);
  some_other_function_using_the_path_string(path);
}

the code above works fine, the reason why i'm posting this is the following.

Why do i have to pass the adress of the pointer "path" to the function enter_path, so some other function can use/read the modified value. So in short, Why do i have to use the &-operand when calling the "enter_path" function, and can't define enter_path as "int enter_path(char* path);"

I know this is normal variables refering to datatypes like int, long, etc. but i assumed that when working with pointers the change should be visible for every other function. cause the pointer still referes to the same point in the memory, just the value has been changed.

Could it be i'm seeing this all wrong?

PS: I'm trying my best to keep my code ansi-C compliant, which is the reason i'm using fgets instead of readline. Just sayin that cause i've allready got some comments regarding the fact that the readline function is easier/safer to use.

With kind regards, JD

like image 542
D Jake Avatar asked Aug 29 '26 01:08

D Jake


1 Answers

If you have a variable of type T that you want a function to be able to modify, you need to pass it via a pointer, i.e.:

void foo(T *p) { *p = 42; }

int main(void) {
    T t;
    foo(&t);
    // The value of t is now 42
}

In your code, T is char *; in other words, your function needs to be able modify a pointer, so you need to pass it a pointer to that pointer.


However, this is not good code. If (**path == '\n') is true, then you will leak memory.

like image 93
Oliver Charlesworth Avatar answered Sep 04 '26 04:09

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!