0
#include<stdio.h>

main()
{
int *A=NULL; 
*A=12; 
printf("The value of the ponter A is=%d",*A); 
}

该程序即将出现分段错误

4

2 回答 2

3

取消引用NULL指针是undefined behaviour

    int *A=NULL; // creating a pointer to int and setting it to NULL
                 //means it points to nothing
    *A=12; // Now you try to dereference it so it's giving seg fault.

另一件事int *A不是NULL指针仍然直接将值分配给指针是无效的手段,

int *A ;
*A=12; // It's invalid too

你应该试试这个:

int a=12;
int *A ;
A=&a; // assign later or you can so it in initialization

编辑:ISO c99 标准:在给定段落的最后一行突出显示

6.5.3.2 地址和间接运算符约束

4    The unary * operator denotes indirection. If the operand points to a function,

 the result is a function designator; if it points to an object, the result is an lvalue 

    designating the object. If the operand has type ‘‘pointer to type’’, the result has 

type ‘‘type’’. If an invalid value has been assigned to the pointer, the behavior of the 

unary * operator is undefined.84)
于 2012-11-22T06:51:26.960 回答
2

您需要为指针分配内存位置A

以下声明

int *A = NULL;

仅声明 A 是指向整数的指针,当前它指向的地址为 NULL。由于写入 NULL 和取消引用 NULL 是未定义的行为,因此您遇到了分段错误。

您需要使用malloc分配内存来解决问题或使指针指向有效对象。

于 2012-11-22T06:53:50.670 回答