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.
You have confused few things.
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
"E" is a string literal (char*) and 'E' is a char literal (char).
Note that the two pieces of code which you are comparing are not analogous! The difference between the two pieces of code (int vs char*) will be clearer is you write
char* mychar = "H";
*mychar = "E";
The type corresponding to the int example is (char*). That is, the code being analog to the "int" example is
char* mychar = "H";
mychar = "E";
String literals might be stored in read-only section of memory. Modifying a string literal invokes undefined behavior. You can't modify it.
Add const qualifier to let your compiler know that string is non-modifiable
char const *mychar = "H";
You should also note that the statement
*mychar = "E";
is wrong by itself. You are assigning a char * type to char.