gpt4 book ai didi

c - 将 void 指针指向 char 指针

转载 作者:行者123 更新时间:2023-12-02 21:21:07 26 4
gpt4 key购买 nike

我有两个指针。一个带有字符串“test”的 char 指针和一个 void 指针。我试图让pointer指向string的地址。这是我的代码:

#include <stdio.h>

int main(){
void *pointer = NULL;
char *string = "test";
*(char*)pointer = &string;

printf("The string address: %p\n", string);
printf("The string: %s\n", string);
printf("The pointer address: %p\n", pointer);
printf("The pointer points to: %p", *(char*)pointer);

return 0;
}

当我将第 6 行的 pointer 设置为等于 string 的地址时,我得到 makes integer frompointer without a Cast。我该如何做到这一点?

编辑:我打印了错误的地址。我的意思是 printf 行看起来像这样:

#include <stdio.h>

int main(){
void *pointer = NULL;
char *string = "test";
pointer = &string;

printf("The string address: %p\n", &string);
printf("The string: %s\n", string);
printf("The pointer address: %p\n", &pointer);
printf("The pointer points to: %p", pointer);

return 0;
}

现在可以正确打印出以下内容:

The string address: 0028FF18
The string: test
The pointer address: 0028FF1C
The pointer points to: 0028FF18

因此,stringpointer是单独的指针,pointer指向string

最佳答案

为什么不简单地做

#include <stdio.h>

int main(){
void *pointer = NULL;
char *string = "test";
pointer = &string; // point to the address of string
printf("The string address: %p\n", string);
printf("The string: %s\n", string);
printf("The pointer address: %p\n", pointer);
printf("The pointer points to: %p\n", (char*)(*(char**)(pointer)));

return 0;
}

关于c - 将 void 指针指向 char 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27638432/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com