0

Why is this erroneous?

char *p;   
*p='a';

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

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

3 Answers3

3

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.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • Ok , do you mean we need to make the pointer to point some location forcefully. And then only it can be used.. I m trying to get an intiution. – Raviraj Gardi Dec 16 '18 at 07:39
  • @RavirajGardi: Yes: if the pointer is not yet pointing to a known location, it cannot be used safely — it can only be assigned to in order to make it point to a defined location or to make it into a null pointer. – Jonathan Leffler Dec 16 '18 at 08:33
  • The pointer can be initialized either by malloc() o by taking the address of other char/char-array, wich already own storage, with & operator (address-of). p=&mycharvar; – ulix Dec 16 '18 at 09:19
  • It’s not always useful (let alone necessary) to allocate heap memory. A pointer can just as easily point to a variable on the stack. We don’t know how the OP wants to use the variable, but stack might be the better option - with less risk of forgetting to free up the memory. See P__J__’s answer for both options. – Jim Danner Dec 16 '18 at 10:56
2

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';
0___________
  • 60,014
  • 4
  • 34
  • 74
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.

kkvaruas
  • 26
  • 3