已初始化的数据成员值不正确地存储在结构中。

huangapple go评论89阅读模式
英文:

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 &lt;&lt; &quot;a: &quot; &lt;&lt; s.a &lt;&lt; &quot; b: &quot; &lt;&lt; (int)s.b &lt;&lt; endl;

huangapple
  • 本文由 发表于 2023年7月11日 13:01:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76658832.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定