很抱歉,如果这篇文章是无知的,但我仍然是C的新手,所以我对它没有太大的了解.现在我正试图找出指针.
我做了这段代码来测试我是否可以在更改函数中更改b的值,并通过传入指针将其转移回main函数(不返回).
但是,我收到一个错误.
Initialization makes pointer from integer without a cast
int *b = 6
Run Code Online (Sandbox Code Playgroud)
据我所知,
#include <stdio.h>
int change(int * b){
* b = 4;
return 0;
}
int main(){
int * b = 6;
change(b);
printf("%d", b);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我真正担心的是修复这个错误,但如果我对指针的理解完全错误,我不会反对批评.
小智 9
为了使其工作重写代码如下 -
#include <stdio.h>
int change(int * b){
* b = 4;
return 0;
}
int main(){
int b = 6; //variable type of b is 'int' not 'int *'
change(&b);//Instead of b the address of b is passed
printf("%d", b);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码将起作用.
在C中,当您希望更改函数中变量的值时,可以"通过引用将变量传递给函数".你可以在这里阅读更多相关信息 - 通过参考
现在错误意味着您正在尝试将整数存储到作为指针的变量中,而不进行类型转换.您可以通过更改该行来消除此错误(但程序将无法工作,因为逻辑仍然是错误的)
int * b = (int *)6; //This is typecasting int into type (int *)
Run Code Online (Sandbox Code Playgroud)