Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pointer is "passed by value"?

After calling f() on ptr, I expect it to point to a single byte with value of A.
But instead ptr is copied by value and it is only available in the f function(?)
What am I doing wrong?

void f(char* ptr) {
    ptr = (char*) malloc(1);
    *ptr = 'A';
}

int main() {
    char* ptr;
    f(ptr);
    printf("%c\n", *ptr); // Segmentation fault, But it should be 'A'
    // free(ptr);
}

Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes, it’s passed by value. If you want the changes you make to the pointer to be visible at the call site, you need to pass a pointer to the pointer.

Example:

#include <stdlib.h>
#include <stdio.h>

void f(char **ptr) {          // pointer to the pointer
    *ptr = malloc(1);
    if(*ptr)                  // precaution if malloc should fail
        **ptr = 'A';
}

int main(void) {
    char *ptr;
    f(&ptr);                  // take the address of `ptr`
    if(ptr)                   // precaution again
        printf("%c\n", *ptr); // now fine
    free(ptr);                // without this, you have a memory leak
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading