Reputation: 11
I'm an absolute beginner to C, I've had some experiences with other high level languages like Ruby and Python, but other than that I'm also a beginner to programming in general. I've been trying to figure out how to define a string variable and print it using something like the "printf" function, but so far I've had no luck since my code just keeps spitting out error messages.
From what I understand, something like this should define a string variable and then print it to the console:
char string[3];
string = "hi";
printf ("%s", string);
But this doesn't work, so what is the correct way to do this?
Upvotes: 0
Views: 109
Reputation: 400019
This doesn't work because you cannot assign to arrays in C, except when initializing them.
So, you can do:
char string[3] = "hi";
which is better (safer) written as:
char string[] = "hi";
this lets the compiler worry about the character-count, and is generally preferable.
To change the array contents after initialization, you must use some function that can copy the characters, you cannot do this with a single assignment:
strcpy(string, "yo");
note that this is dangerous since strcpy()
will not be aware of the array's limit of 3 characters.
Upvotes: 4