Pointer initialization concept in C

旧街凉风 提交于 2019-12-13 08:34:59

问题


Why is this erroneous?

char *p;   
*p='a';

The book only says -use of uninitialized pointer. Please can any one explain how that is?


回答1:


char *c; //a pointer variable is being declared 
*c='a';

you used the dereferencing operator to access the value of the variable to which c points to but your pointer variable c is not pointing to any variable thats why you are having runtime issues.

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

Hope this helped.




回答2:


Yes, it may cause a run-time error since it is undefined behavior. The pointer variable is defined (but not properly initialized to a valid memory location), but it needs memory allocation to set value.

char *p;
p = malloc(sizeof(char));
*p = 'a';

It will work when malloc succeeds. Please try it.




回答3:


The pointer is not initialized ie it does not point to object allocated by you.

char c;
char *p = &c;
*p = 'c';

Or

char *p = malloc(1);
*p = 'c';


来源:https://stackoverflow.com/questions/53800196/pointer-initialization-concept-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!