1

I want to pass a char pointer to a function and have it set the value and pass it back. Here is my attempt but the printf prints garbage, where am I going wrong?

int a() {
    char *p;    
    b(p);    
    printf("%s", p);
    return 0;
}

int b(char * ptr) {
    ptr = "test string";
    return 0;
}

2 Answers 2

3

Pass a reference to the pointer.

int b(char  **ptr)
{
    *ptr = "Print statement";
    //your code
}
//call
b(&p);
Sign up to request clarification or add additional context in comments.

3 Comments

I know this is nitpicking but I would change char ** to const char** because it is a constant string.
i myself am not well-versed in use of const pointer, so can't suggest that.
"Print statement" is a constant string and will most likely be placed inside the read-only section of the executable. Modifying it will result in a crash. const char * ''prevents'' the modification of the string.
2

If you want to set the value of the pointer and pass it back, then b() needs to return a pointer:

int a(void) {
    char *p = NULL;    
    p = b(p);    
    printf("%s", p);
    return 0;
}

char * b(char * ptr) {
    ptr = "test string";
    return ptr;
}

Here p is initialized to NULL to avoid undefined behavior from passing an uninitialized value to a function. You could also initialize p to another string literal. Inside b, ptr is a copy of the pointer p that was passed to b. When you reassign the value stored in ptr to the address of the string literal "test string", the original pointer p is unchanged. By passing ptr back to the calling function, and reassigning p to the return value of b, the calling function can use the updated value.

As @M.M points out in the comments, this is somewhat redundant. The function b() could instead declare a pointer of its own, initialized to a string literal:

int a(void) {
    char *p = b();    
    printf("%s", p);
    return 0;
}

char * b(void) {
    char *ptr = "test string";
    return ptr;
}

2 Comments

You meant to give b a return type of char *. But in this code the function parameter is redundant and should be removed. (In fact b(p) causes undefined behaviour by using an uninitialized pointer value).
@M.M-- Thanks for the comment. I think that everything is fixed now. I believe that C11 §6.3.2.1 2 about lvalue conversion is the relevant section for the undefined behavior that you describe: "If the lvalue designates an object of automatic storage duration... and that object is uninitialized..., the behavior is undefined." If there is another citation that better fits this situation, please pass it along.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.