为什么像这样使用指针会导致构建崩溃?
Why Using Pointer Like This Is Crashing The Build?
我正在深入研究 C 中的指针,但是当我编写一个简单的代码来解决这个问题时,就会发生这种情况。
IDE : Code::Blocks
OS: Windows 8.1
#include <stdio.h>
int main(){
int x;
x = 6;
int* p;
*p = &x; // This is wrong
printf("%d\n",*p);
}
您需要更改 *p = &x;
。请改用 p = &x;
。
它正在崩溃,因为您在未初始化的指针上使用 *p
。当您声明 int* p;
时,p
的初始化值未被 C 语言 规范定义。您还试图将地址 (&x
) 分配给 int
占位符(*p
,p
指向的值)。
因此,当您尝试通过执行 *p
取消引用下一句中的 p
指针时,您可能正在尝试访问您的进程不可用的内存位置。
p = &x; // you are pointing p to x variable memory location
printf("%d\n",*p); // should print 6
*p = 10;
printf("%d\n",*p); // should print 10
printf("%d\n",x); // should also print 10
我正在深入研究 C 中的指针,但是当我编写一个简单的代码来解决这个问题时,就会发生这种情况。
IDE : Code::Blocks
OS: Windows 8.1
#include <stdio.h>
int main(){
int x;
x = 6;
int* p;
*p = &x; // This is wrong
printf("%d\n",*p);
}
您需要更改 *p = &x;
。请改用 p = &x;
。
它正在崩溃,因为您在未初始化的指针上使用 *p
。当您声明 int* p;
时,p
的初始化值未被 C 语言 规范定义。您还试图将地址 (&x
) 分配给 int
占位符(*p
,p
指向的值)。
因此,当您尝试通过执行 *p
取消引用下一句中的 p
指针时,您可能正在尝试访问您的进程不可用的内存位置。
p = &x; // you are pointing p to x variable memory location
printf("%d\n",*p); // should print 6
*p = 10;
printf("%d\n",*p); // should print 10
printf("%d\n",x); // should also print 10