结构上的一些问题
Some problems with struct
#include <iostream>
using namespace std;
struct student{
char name[10];
int grade;
};
int main() {
struct student s[10];
student s[0].name = "Jack";
cout<<s[0].name;
}
我想创建结构类型数据student
作为数组。但是当我这样做的时候,出现了一些错误,我不知道为什么。以下是错误:
1。错误:用不同的类型重新定义's': 'student[0]'与'struct student [10]'
student s[0].name = "Jack";
^
2。注:前面的定义在这里
struct student s[10];
^
3。错误:声明结束
student s[0].name = "Jack";
^
;
-
char name[10];
:-
10
字符对于名称来说太短。 -
char
假定名称不在ASCII或UTF-8之外,并且看起来不像您正在使用Unicode库。 - 用于存储字符串的固定大小数组不符合c++的习惯。
- 解决方案:使用
std::string
或std::wstring
-并使用Unicode库!
-
-
struct student s[10]
- 这不是惯用的c++。不需要使用
struct
关键字。只要student s[10];
就足够了。 同样,避免固定大小的数组,除非您确定将使用10条记录。使用
std::vector<student>
代替。 你没有初始化数组,所以数据成员将包含未定义/未初始化的数据。使用 - 这不是惯用的c++。不需要使用
= {0}
来清空内存和/或定义student
构造函数。student s[0].name = "Jack";
- 无法编译。我想你的意思是把
s[0].name = "Jack"
- 没有为字符串定义赋值操作符
=
(默认情况下)。请注意,您的结构体的成员类型是char
,而字符串字量是const char[N]
,因此实际上您将指针(由于数组衰减)分配给char
成员。这个操作没有意义。
main
没有返回值。成功时使用return EXIT_SUCCESS;
。这不是严格要求的,但我个人认为显式返回一个值是很好的实践。 相关文章:
- 将字符数组转换为结构时出现问题. 结构的字符数组变量溢出
- sizeof 函数如何在带和不带位字段的结构上工作?(填充)
- 未使用的 asm() 在不受支持的体系结构上的行为
- 复制引用结构上的赋值
- 有了memory_order_relaxed,原子变量的总修改顺序如何在典型体系结构上得到保证
- C 嵌套结构上的 g++ 编译错误
- 结构上溢出的整数加法
- 在通过 P/Invoke 获取的 C++ 结构上设置 C# 回调
- 在包含浮点数的结构上使用 memset()
- 在模板化数据结构上调用 begin() 或 end()
- 在现有数据结构上使用BGL算法需要什么(边和顶点作为矢量<对象*>)?
- boost :: Spirit :: Karma语法:逗号从结构上划定了带有选件属性的输出
- 使用提升库在队列和堆栈数据结构上保存和加载数据时出错
- 所有结构上的奇怪内存位移
- 是在同一体系结构上运行的静态编译的纯标准C 程序可移植
- 在英特尔x86体系结构上使用非AVX指令修改xmm整数寄存器值
- 结构上的内存分配和复制构造函数
- 结构上的 C++ 中的比较器函数
- 用载体建立在苍蝇递归结构上
- 结构上的一些问题