how to pass a string "Hello World" to the field of the structure ?
You have first to declare sufficient memory space for test
array to contain your desired string. the "Hello World"
contains 11 charachters. so your array should contains at least 12 elements
struct main_s {
char test[12];
};
and then copy your string into the array with:
struct main_s m;
strcpy(m.test, "Hello World");
printf("%s\n", m.test) // this display the content of your char array as string
If you want to declare a 2D array:
struct main_s {
char test[3][13];
}
struct main_s m;
strcpy(m.test[0], "Hello World0");
strcpy(m.test[1], "Hello World1");
strcpy(m.test[2], "Hello World2");
printf("%s\n%s\n%s\n", m.test[0], m.test[1], m.test[2]);
The
strcpy(m.test[1], "Hello World1");
is equivalent to:
m.test[1][0]='H';
m.test[1][1]='e';
m.test[1][2]='l';
.
.
m.test[1][10]='d';
m.test[1][11]='1';
m.test[1][12]='\0'; //add null charachter at the end. it's mandatory for strings
The above code are not allowed
m.test[1] = "Hello World1";
m.test[1] = {'H','e','l','l','o',' ','W','o','r','l','d','1'};