Reputation: 409
I am a noob to C programming (I come from the lands of JS and PHP), and as a learning exercise I attempted to write a program that asks for the user's name, and then prints it back out with the small exception of changing the first letter to a z
. However, when I went to compile the code it returned the following error
message in reference to the line name[0] = "Z";
warning: assignment makes integer from pointer without a cast
Is there a reason I can't assign a value to a specific index in a char
array
?
(Note: I have tried typecasting "Z"
to a char but it just threw the error
warning: cast from pointer to integer of different size`)
Upvotes: 0
Views: 156
Reputation: 726809
Unlike some languages that do not distinguish between strings and characters, C requires a different syntax for characters (vs. a single-character string).
You need to use single quotes:
name[0] = 'Z';
The error is quite cryptic, though. It is trying to say that "Z"
, a single-character C string, gets assigned to name[0]
, an integral type of char
. C strings are arrays; arrays are convertible to pointers. Hence, C treats this as a pointer-to-int assignment without a cast.
Upvotes: 5
Reputation: 402813
In C, single quotes and double quotes carry different meanings. In fact, there is no concept of "Strings" in C. You have the basic char data type, where a char is represented by single quotes. To represent strings, you store them as an array of chars. For example,
char text[] = {'h', 'e', 'l', 'l', 'o'};
This is just a more tedious way of writing
char text[] = "hello";
This is exactly the same as the first example, with the exception that there is a null character \0
at the end (this is how C detects the end of "strings"). It's the same as saying char text[] = {'h', 'e', 'l', 'l', 'o', '\0'};
except now you can work with your array more easily, if you want to do string based processing on it.
Coming to your question, if you want to index a certain character in a "string", you'd need to access it by it's index in the array.
So, text[0]
returns the character h
which is of type char
. To assign a different value, you must assign a single quoted char as so:
text[0] = 'Z';
Upvotes: 2
Reputation: 4111
replace name[0] = "Z";
with name[0] = 'Z';
.
'single-quatation' is for an character element
and "double-quatation" is for a string assignment.
Upvotes: 4