char和char有什么区别[1]?

ifsvaxew  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(69)
#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);
}

字符串
在这段代码中,在std变量中分配性别字符时出错。我认为'M'只有一个字符,所以它将像正常变量一样在结构中工作。

#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);
}


我修改了这样的代码,然后它就可以工作了。
所以我的问题是,
1.在内存透视中,char和char [1]有什么不同?
1.为什么字符性在结构中不起作用?
我找了,但是找不到答案。帮帮我!

f0brbegy

f0brbegy1#

char是一个标量类型,而char[1]是一个只有一个元素的数组类型。"M"是一个字符串文字,具有字符数组类型char[2],在内存中存储为{ 'M', '\0' }
您可以使用printf调用来检查

printf( "sizeof( \"M\" ) = %zu\n", sizeof( "M" ) );

字符串
本声明中

std.sex="M";


你试图将数组(字符串字面量)"M"赋值给char类型的标量对象std::sex。在这个赋值中,字符数组被隐式转换为指向它的第一个元素的指针。实际上,你有

std.sex = &"M"[0];


而你至少要写

std.sex = "M"[0];


尽管使用整数字符常量而不是字符串字面量会更简单明了,

std.sex = 'M';


相应地,在调用printf时,您应该使用转换说明符c而不是s来输出单个字符。

printf("%d %s %c %d\n", std.id, std.name, std.sex, std.grade);
              ^^


在第二个程序中,数据成员sex被声明为一个只有一个元素的数组。

char sex[1];


那么这个调用strcpy

strcpy(std.sex, "M");


写入数组sex之外的内存,因为如上所述,字符串"M"有两个元素。因此,第二个程序也是无效的。它似乎只由于数据成员int grade;的对齐,即编译器在数据成员sex之后插入额外的字节来提供对齐。
你可以像这样声明字符数组

char sex[2];


虽然你只需要使用一个字符,那么将数据成员sex声明为

char sex;


并在第一个程序的注解中使用它。
请注意,您可以通过以下方式在声明中初始化结构类型的对象

struct Student std = 
{
    .id = 1, .name = "Kevin", .sex = 'M', .grade = 2
};


struct Student std = 
{
    1, "Kevin", 'M', 2
};

相关问题