struct employee
{
char name[20];
}emp;
void main()
{
emp.name[20]="John";
printf("%s\n",emp.name);
}
why does this code give no output? Why is it impossible to initialize the string array directly?
First: Your compiler should warn you. If you use gcc, try compiling this with
gcc -std=c11 -Wall -Wextra -pedantic
and see.
The issue is just wrong syntax. you're assigning your string literal to emp.name[20] which is the 21st element of emp.name. This element doesn't even exist and it has the type char.
What you want would be something like:
emp.name = "John"; // <- INVALID!!
But this doesn't work, because C unfortunately doesn't allow to assign to an array. You can use the function strcpy (string copy) to achieve what you want, though (include string.h):
strcpy(emp.name, "John");
The statement emp.name[20]="John"; has a few problems. The intention appears to be to assign the string "John" to the character array emp.name. But, you can't assign to character arrays (you can initialize them). "John" is a string literal, which decays to a pointer to the first element of an array of char in the assignment expression, so this statement is attempting to assign a pointer to char to emp.name[20], which isn't a character array anyway, but would be a char, except that emp.name[20] is an attempted out-of-bounds array access. Remember that arrays are zero-indexed in C, so the first element of the array is emp.name[0], and the last index is emp.name[19]. Finally, even if this assignment was to a valid element of the array, you certainly don't mean to assign a pointer to a char.
One solution would be to make emp local to main(), and use an initializer. Note that the function signature for main() should be one of int main(void) or int main(int argc, char **argv); any other function signature here is implementation-dependent. Also, I assume that the original code did not forget to #include <stdio.h>.
#include <stdio.h>
struct employee
{
char name[20];
};
int main(void)
{
struct employee emp = { .name = "John" };
printf("%s\n",emp.name);
return 0;
}
Alternatively, you could use strcpy() without changing emp. One disadvantage to this approach is that you must be careful not to attempt to copy a string larger than emp.name[]:
#include <stdio.h>
#include <string.h>
struct employee
{
char name[20];
} emp;
int main(void)
{
strcpy(emp.name, "John");
printf("%s\n",emp.name);
return 0;
}
The designated initializer could have also been used at file scope with the original struct like this:
#include <stdio.h>
struct employee
{
char name[20];
} emp = { .name = "John" };
int main(void)
{
printf("%s\n",emp.name);
return 0;
}
Emp.name[20] is taking the index of the 20th position of the array name. So it will throw an error.
U can write ur code in this way using
strcpy()
#include <stdio.h>
#include<string.h>
struct employee
{
char name[20];
}emp;
void main()
{
// emp.name="John";
strcpy(emp.name,"john");
printf("%s\n",emp.name);
}
'\0'.