简体   繁体   English

c指针分割故障

[英]c pointers segmentation fault

CASE 1: 情况1:

#include <stdio.h>
int main()
{
 int a = 5,*p;
 *p = &a;
  printf("%d",*p);
 }

the above mentioned program gives the segmentation fault problem. 上述程序给出了分割错误的问题。 but in the case 2 it works fine. 但在第2种情况下,效果很好。 CASE 2: 情况2:

#include <stdio.h>
int main()
{
int a = 5,*p = &a;
printf("%d",*p);
}

can anyone please explain this problem. 谁能解释这个问题。 Thank you. 谢谢。

*p = &a;

Dereferences p and assigns &a to the memory location p is pointing to . 取消引用p并将&a分配给p 指向的存储位置。 The pointer is uninitialized, so dereferencing it yields undefined behavior (thus the segmentation fault). 指针是未初始化的,因此取消引用它会产生未定义的行为 (因此出现分段错误)。

int a = 5,*p = &a;

Defines a and p , where the asterisk doesn't indicate dereferencing but distinguishes a usual int definition from a int* pointer definition. 定义ap ,其中星号不表示取消引用,而是将通常的int定义与int*指针定义区分开。 The line is equivalent to 该行相当于

int a = 5;
int* p = &a;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM