为什么这是错误的?
char *p;
*p='a';
这本书只说 - 使用未初始化的指针。请任何人解释这是怎么回事?
是的,它可能会导致运行时错误,因为它是未定义的行为。指针变量已定义(但未正确初始化为有效的内存位置),但需要分配内存来设置值。
char *p;
p = malloc(sizeof(char));
*p = 'a';
成功时它将起作用 malloc
。请尝试一下。
指针未初始化,即它不指向您分配的对象。
char c;
char *p = &c;
*p = 'c';
或者
char *p = malloc(1);
*p = 'c';
char *c; //a pointer variable is being declared
*c='a';
您使用取消引用运算符来访问 c 指向的变量的值,但您的指针变量 c 未指向任何变量,这就是您遇到运行时问题的原因。
char *c; //declaration of the pointer variable
char var;
c=&var; //now the pointer variable c points to variable var.
*c='a'; //value of var is set to 'a' using pointer
printf("%c",var); //will print 'a' to the console
希望这有帮助。