Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, why can't the value of a pointer-to-char variable be changed after it has been assigned?

I don't understand the difference between this case:

#include <stdio.h>

int main()
{
  int i = 0;
  i = 1;

  return 0;
}

And this case:

#include <stdio.h>

int main()
{
  char *mychar = "H";
  *mychar = "E";

  return 0;
}

Which produces the compiler warning "assignment makes integer from pointer without a cast".

Shouldn't *mychar = "E" dereference mychar to assign it the value of "E"?

Many thanks.

like image 269
sav0h Avatar asked Jul 25 '15 16:07

sav0h


People also ask

Can a const char * Be Changed?

const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed.

What happens when you cast a char pointer to an int pointer?

When casting character pointer to integer pointer, integer pointer holds some weird value, no where reasonably related to char or char ascii code. But while printing casted variable with '%c', it prints correct char value. Printing with '%d' gives some unknown numbers.

Can a pointer be char?

A character pointer is again a pointer like the pointers to other types in C. Here ptr is pointer to a character. A point to note here is - pointer to a character is different from the pointer to a string. In C, strings are defined as an array of characters.

Can you increment a char pointer?

For example, incrementing a char pointer will increase its value by one because the very next valid char address is one byte from the current location. Incrementing an int pointer will increase its value by four because the next valid integer address is four bytes from the current location.

Can pointer work on string in c?

A pointer to a string in C can be used to point to the base address of the string array, and its value can be dereferenced to get the value of the string.


1 Answers

You have confused few things.

  • Note "E" is actually const char[] which stores 'E' and '\0'. It is not a single character. For single characters you use '', like 'E'.
  • mychar points to string literal and you can't change string literals.

If what you had in mind is this:

 char *mychar = "H";
 mychar = "E"; 

This is ok, you are not changing the string literal, just first time the pointer mychar points to string literal "H", then to "E".

This you can't do:

  char *mychar = "Hello";
  *mychar = 'E'; // Can't modify the string literal

But this you can do:

  char c = 0;
  char *mychar = &c;
  *mychar = 'E'; // This is ok
like image 54
Giorgi Moniava Avatar answered Sep 29 '22 18:09

Giorgi Moniava