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...
struct person me = {"nikol", 3};
should work. – Adversary