C指针的初始化和取消引用,这是怎么回事? [英] C pointer initialization and dereferencing, what's wrong here?
问题描述
这应该超级简单,但是我不确定为什么编译器会在这里抱怨.
This should be super simple, but I'm not sure why the compiler is complaining here.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int *n = 5;
printf ("n: %d", *n);
exit(0);
}
收到以下投诉:
foo.c:在"main"函数中:
foo.c:6: 警告:初始化会使指针 从没有强制转换的整数
foo.c: In function ‘main’:
foo.c:6: warning: initialization makes pointer from integer without a cast
我只想打印指针n引用的值.我在printf()语句中取消引用它,但遇到了分段错误.用gcc -o foo foo.c编译.
I just want to print the value that the pointer n references. I'm dereferencing it in the printf() statement and I get a segmentation fault. Compiling this with gcc -o foo foo.c.
推荐答案
您将指针设置为内存地址5
,使其指向地址5
处的任何内容.您可能想使其指向存储值5
的地址.例如:
You set the pointer to memory address 5
, so that it points to whatever at address 5
might be. You probably wanted to make it point to an address where the value 5
is stored. For example:
int v = 5; // Store the value 5 in a normal variable
int *n = &v; // Make n contain the address of v, so that it points to the
// contents of v
这篇关于C指针的初始化和取消引用,这是怎么回事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!