繁体   English   中英

如何修复 C 代码中的指针问题?

[英]How can I fix pointer problem in my C code?

#include <stdio.h>
void test(void **arg) {
    int foo = 3;
    **(int **)arg = foo; // I want to just fix this line!!
}

int main(void) {
    int temp = 0;
    printf("%d\n", temp);

    test((void **)&temp);

    printf("%d\n", temp);

    return 0;
}

在我的代码中,它有问题“分段错误”,但我不知道如何修复我的代码..

我只想修复**(int **)arg = foo; 线。

有谁能够帮我?

在您的代码中, function test(void **temp) ,变量 temp 是指向指针的指针,也就是双指针。 也就是说,它的值是一个地址。 但是当你从 main 调用 test 时,那个值是 0,这意味着地址是地址 0。

您不能为地址 0 分配值。

看起来您正在写入地址 0。

因为:

&temp是一个指向 int 的指针。

*((int**)&temp)是一个整数。

**((int**)&temp)使用来自 temp 的值作为地址。

你的 function

void test(void **arg);

需要一个“指向 void 的指针” ,即包含另一个指向通用数据的地址的位置的地址。

当您调用 function 时,您没有通过它的预期

int temp = 0;
test((void **)&temp);

事实上&temp是一个指向 integer 的地址。 但是它需要一个地址的地址,因此,当在 function 内部时,您在第二次尝试访问地址 0 时将其延迟两次(使用*运算符的每次延迟都意味着“解析”一个地址)。

为了修复它,只需通过test指向指针的指针:

int temp = 0;
int *tempAddr = &temp; //tempAddr points to temp

test((void **)&tempAddr); //The type of the address of tempAddr is 'int  **'

您实际上是在问另一件事:您明确要求修复**((int **) arg) = foo; 线。

这并不容易,因为您当前收到了一个无效的指针指针,并且仅更改该行就无法使其有效。 为了解决它,您需要更改test()接口,如下所示:

#include <stdio.h>
void test(void *arg) { // changed 'void **' to 'void *'
    int foo = 3;
    *(int *)arg = foo; // only one level of dereferencing
}

int main(void) {
    int temp = 0;
    printf("%d\n", temp);

    test((void *)&temp); // cast to 'void *' instead of 'void **'

    printf("%d\n", temp);

    return 0;
}

暂无
暂无

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

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