我用C制作了这个程序,我收到一个错误,我不知道如何修复.请帮我找错.这是我写的代码:
#include <stdio.h>
int main(int argc, char *argv[]){
int x = 98;
int *g = x;
printf("This is x: %d, and this is g: %i.\n", x, *g);
*g=45;
printf("This is x: %d, and this is g: %i.\n", x, *g);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器给我以下错误:
ex15t.c: In function ‘main’:
ex15t.c:5:12: warning: initialization makes pointer from integer without a cast [enabled by default]
Run Code Online (Sandbox Code Playgroud)
在此先感谢任何帮助.
第一行:int * g = x;定义g类型变量int *,然后x为其赋值.
扩展了,这可以解读为:
int *g;
g = x;
Run Code Online (Sandbox Code Playgroud)
这显然不是你想要的,x类型int和g类型int *.
假设您想要g指向变量x,而是执行此操作
int * g = &x;
Run Code Online (Sandbox Code Playgroud)
或者做这个,这可能更清楚:
int *g;
g = &x;
Run Code Online (Sandbox Code Playgroud)
目前你正在向指针指示x中的任何值(98),并且一个int不是指示它警告你的指针.你真正想要的是得到x所在的地址,即指向x的位置.所以....
int *g = x;
Run Code Online (Sandbox Code Playgroud)
需要是
int *g = &x;
Run Code Online (Sandbox Code Playgroud)