In C, why can't I assign a string to a char array after it's declared?
Arrays are second-class citizens in C, they do not support assignment.
char x[] = "This is initialization, not assignment, thus ok.";
This does not work:
x = "Compilation-error here, tried to assign to an array.";
Use library-functions or manually copy every element for itself:
#include <string.h>
strcpy(x, "The library-solution to string-assignment.");
me.name = "nikol";
is wrong !! you need to use strcpy()
when you do x = "Some String"
, actually you are putting the starting address of the static string "Some String"
into variable x
. In your case, name
is a static array, and you cannot change the address. What you need, is to copy your string to the already allocated array name
. For that, use strcpy()
.
First of all, you need to know the following points:
- In C, text strings are just arrays.
- In C, array variables are basically just pointers.
So, char mytext[12];
is essentially just declaring a char pointer called mytext
that stores the address of the first (zero'th) element of the array/string.
This code is therefore valid:
#include <stdio.h>
int main(int argc, char *argv[])
{
const char a[] = "Hello";
const char *b = a;
printf("%s\n", b);
return 0;
}
The important thing to note here is that re-assigning b
doesn't change the contents of whatever it points to - it changes the thing that it points to.
However, there are cases where arrays and pointers behave differently. In the example above, a
cannot be reassigned. If you try, you'll get an error.
To go back to you original example, this structure:
struct person{
char name[15];
int age;
};
...can be thought of as a 19-byte structure* of which the first 15 bytes are earmarked for storing a string. The name
attribute stores the address of the first byte, so you know where those 15 bytes live in memory - you just need to write something useful into them.
This is where functions such as sprintf()
or strcpy()
come into play - they copy data into the address defined by name
rather than re-assigning name
itself.
* Assuming that sizeof(int)
is 4 and the structure is not padded, of course...