Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing pointer to C array to a function

Tags:

c

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;
}
like image 294
Motiejus Jakštys Avatar asked Nov 05 '22 05:11

Motiejus Jakštys


1 Answers

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;
like image 180
Constantinius Avatar answered Nov 09 '22 13:11

Constantinius