5

What do I misunderstand about passing pointers to char arrays?

Request pointer in fun: 0x7fffde9aec80
Response pointer in fun: 0x7fffde9aec80
Response pointer: (nil), expected: 0x7fffde9aec80
Response itself: (null), expected: Yadda
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int get_response(char *request, char **response) {
    response = &request;
    printf("Request pointer in fun: %p\n", request);
    printf("Response pointer in fun: %p\n", *response);
    return 0;
}

int main() {
    char *response = NULL, request[] = "Yadda";

    get_response(request, &response);

    printf("Response pointer: %p, expected: %p\n", response, request);
    printf("Response itself: %s, expected: %s\n", response, request);

    return 0;
}
2
  • 3
    I don't know. Which part do you not understand? Commented Feb 23, 2012 at 14:12
  • @OliCharlesworth: He doesn't get why what gets printed does not match what he 'expects' to be printed: Response pointer: (nil), expected: 0x7fffde9aec80 Response itself: (null), expected: Yadda Commented Feb 23, 2012 at 14:18

4 Answers 4

2

in the function get_response you store the address of request in the temporary variable response. You want to store it where response points to.

*response = request;
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for explaining what OP is 'misunderstanding'. i.e. changing an argument's value instead of changing the location which the argument points to.
0

Try *response = request: you want to set the contents of the response pointer to the request content.

Comments

0

You want *response = request; instead of response = &request; in get_response(...)

Comments

0

Firstly, with the currect declaration and your usage of get_response, the parameter response is declared as char**, which is a pointer to a char*, e.g. a pointer to a pointer. This would be useful if you somehow needed to modify the pointer actually pointing to the memory containing your response, but in this case this is not needed.

Comments

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.