#include <stdio.h>
#include <string.h>
struct Student {
int id;
char name[10];
char sex;
int grade;
};
int main() {
struct Student std;
std.id = 1;
strcpy(std.name, "Kevin");
std.sex="M";
std.grade = 2;
printf("%d %s %s %d\n", std.id, std.name, std.sex, std.grade);
}
In this code, got error on allocating a sex character in std variable. I thought 'M' is only one character so that It will works in structure like normal variable did.
#include <stdio.h>
#include <string.h>
struct Student {
int id;
char name[10];
char sex[1];
int grade;
};
int main() {
struct Student std;
std.id = 1;
strcpy(std.name, "Kevin");
strcpy(std.sex, "M");
std.grade = 2;
printf("%d %s %s %d\n", std.id, std.name, std.sex, std.grade);
}
I fixed code like this then it works.
So my question is,
- What's different between char and char [1] in memory perspection?
- Why char sex doesn't work in structure?
I seached but can't find answer. Help me!
charis a scalar type whilechar[1]is an array type with one element."M"is a string literal that has character array typechar[2]and in memory is stored like{ 'M', '\0' }.You can check that using this call of
printfIn this statement
you are trying to assign the array (string literal)
"M"to the scalar objectstd::sexof the typechar. In this assignment the character array is implicitly converted to a pointer to its first element. In fact you havewhile you need to write at least like
though instead of the string literal it will be simpler and clear to use an integer character constant like
Correspondingly in the call of
printfyou shall use conversion specifiercinstead ofsto output a single characterIn the second program as the data member
sexis declared as an array with one elementthen this call of
strcpywrites into memory outside the array
sexbecause as pointed out above the string literal"M"has two elements. As a result the second program is also invalid. It seems it works only due to the alignment of the data memberint grade;that is the compiler inserts additional bytes after the data membersexto provide the alignment.You could declare the character array like
though as you are going to use only one character then it will be enough to declare the data member
sexasand use it as shown above in the comments for the first program.
Pay attention to that you could initialize the object of the structure type in its declaration the following way
or