简体   繁体   English

将指向C数组的指针传递给函数

[英]Passing pointer to C array to a function

What do I misunderstand about passing pointers to char arrays? 关于将指针传递给char数组,我有什么误解?

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;
}

in the function get_response you store the address of request in the temporary variable response . 在函数get_response您将request的地址存储在临时变量response You want to store it where response points to. 您希望将其存储在response 所在的位置

*response = request;

尝试*response = request :您想要将响应指针的内容设置为请求内容。

You want *response = request; 你想要*response = request; instead of response = &request; 而不是response = &request; in get_response(...) get_response(...)

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* , eg a pointer to a pointer. 首先,使用当前声明和get_response的使用,参数response被声明为char** ,它是指向char*的指针,例如指向指针的指针。 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. 如果你以某种方式需要修改实际指向包含你的response的内存的指针,这将是有用的,但在这种情况下,这是不需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM