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.
const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With