首页 > 解决方案 > 为什么 char 数组在动态结构数组中不起作用?

问题描述

我试图了解 C++ 中的结构。我想制作一个动态结构数组,用一些值对其进行初始化,然后在屏幕上查看这些值。为什么它在使用字符串时有效,而在使用 char 数组时无效。

#include <iostream>

struct batonik
{
char name[20];
double weight;
int calories;
};

int main()
{
batonik *ps = new batonik[3]
{
    { "snickers",2.2,350 },
    { "mars",2.6,420 },
    { "bounty",2.1,210 }
};
for (int i = 0; i < 3; i++)
{
    std::cout << "Nazwa batonika : " << (*(ps+i)).name << std::endl;
    std::cout << "Waga batonika : " << (ps+i)->weight << std::endl;
    std::cout << "Ilosc kalorii : " << (ps+i)->calories<< std::endl;
    std::cout << i;
}
delete [] ps;
return 0;
}

标签: arraysstruct

解决方案


推荐阅读