问题
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