英文:
Initialized data member values incorrectly stored in struct
问题
问题场景
#include <iostream>
using namespace std;
struct sec
{
int a;
char b;
};
int main()
{
struct sec s ={25,50};
cout << "struct sec的大小: " << sizeof(s) << endl;
cout << "a: " << s.a << " b: " << s.b << endl;
return 0;
}
输出:
struct sec的大小: 8
a: 25 b: 2
"a = 25"和"b = 50"结构数据成员的初始值。然而,保存的值不正确。
适用于整数类型。
#include <iostream>
using namespace std;
struct sec
{
int a;
char b;
};
int main()
{
struct sec s ={25,50};
cout << "struct sec的大小: " << sizeof(s) << endl;
cout << "a: " << s.a << " b: " << s.b << endl;
return 0;
}
输出:
struct sec的大小: 8
a: 25 b: 50
英文:
Problematic scenario
#include <iostream>
using namespace std;
struct sec
{
int a;
char b;
};
int main()
{
struct sec s ={25,50};
cout << "size of struct sec: " << sizeof(s) << endl;
cout << "a: " << s.a << " b: " << s.b << endl;
return 0;
}
output:
size of struct sec: 8
a: 25 b: 2
Initial values for the "a = 25" and "b = 50" struct data members. however the incorrect value was saved.
Works for integer types.
#include <iostream>
using namespace std;
struct sec
{
int a;
char b;
};
int main()
{
struct sec s ={25,50};
cout << "size of struct sec: " << sizeof(s) << endl;
cout << "a: " << s.a << " b: " << s.b << endl;
return 0;
}
output:
size of struct sec: 8
a: 25 b: 50
答案1
得分: 3
你正在打印一个值为50的字符,这是ASCII代码表示的数字'2'。尝试:
cout << "a: " << s.a << " b: " << (int)s.b << endl;
英文:
You are printing a char of value 50, which is the ascii code for '2'. Try:
cout << "a: " << s.a << " b: " << (int)s.b << endl;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论