C语言 打印出指针指向的值(C 编程)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19483918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing out the value pointed by pointer (C Programming)
提问by Pavan
I would like to print out the contents a pointer pointing to. Here is my code:
我想打印出一个指针指向的内容。这是我的代码:
int main(){
int* pt = NULL;
*pt = 100;
printf("%d\n",*pt);
return 0;
}
This gives me a segmentation fault. Why?
这给了我一个分段错误。为什么?
回答by LihO
These lines:
这些线路:
int* pt = NULL;
*pt = 100;
are dereferencing a NULLpointer (i.e. you try to store value 100into the memory at address NULL), which results in undefined behavor. Try:
正在取消引用一个NULL指针(即您尝试将值100存储到地址处的内存中NULL),这会导致未定义的行为。尝试:
int i = 0;
int *p = &i;
*p = 100;
回答by John3136
Because you are trying to write to address NULL.
因为您正在尝试写入地址 NULL。
Try:
尝试:
int main(){
int val = 0;
int* pt = &val;
*pt = 100;
printf("%d\n",*pt);
return 0;
}

