c++ - 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; }
i want create struct type data student
arraign. when did this, errors appeared , didn't know why.following errors:
1.error: redefinition of 's' different type: 'student [0]' vs 'struct student [10]'
student s[0].name = "jack"; ^
2.note: previous definition here
struct student s[10]; ^
3. error: expected ';' @ end of declaration
student s[0].name = "jack"; ^ ;
char name[10];
:10
characters short name.char
assumes names not outside ascii or utf-8, , doesn't you're using unicode library.- fixed-sized arrays storing strings not keeping idiomatic c++.
- solution: use
std::string
orstd::wstring
- , use unicode library!
struct student s[10]
- this not idiomatic c++.
struct
keyword unnecessary.student s[10];
sufficient. - again, avoid fixed-sized arrays unless know using 10 records. use
std::vector<student>
instead. - you don't initialize array, data-members contain undefined/uninitialized data. use
= {0}
zero-out memory and/or definestudent
constructor.
- this not idiomatic c++.
student s[0].name = "jack";
- this won't compile. think meant put
s[0].name = "jack"
- the assignment operator
=
not defined (by default) strings. note struct's member typechar
whereas string literalconst char[n]
, in reality you're assigning pointer (due array decay)char
member. meaningless operation.
- this won't compile. think meant put
- your
main
not return value. usereturn exit_success;
on success. not strictly required, believe it's practice explicitly return value.
Comments
Post a Comment