C++动态数组输出乱码的问题

C++动态数组输出乱码的问题

问题描述:

为何输出成员brand是乱码“屯”?
#include
#include
using namespace std;
int main()
{
struct CandyBar
{
char brand[20];
float weight;
int calorie;
};

CandyBar *test=new CandyBar[3];
test[0].brand =="The First";
test[0].weight=5;
test[0].calorie=136;
test[1].brand =="The Second";
test[1].weight=10;
test[1].calorie=350;
test[2].brand=="The Third";
test[2].weight=15;
test[2].calorie=333;
cout<<"The Brand: "<<test[0].brand;
cout<<", "<<test[1].brand;
cout<<", "<<test[2].brand<<endl;
cout<<endl;
cout<<"The Weight: "<<test[0].weight;
cout<<", "<<test[1].weight;
cout<<", "<<test[2].weight<<endl;
cout<<endl;
cout<<"The Calorie: "<<test[0].calorie;
cout<<", "<<test[1].calorie;
cout<<", "<<test[2].calorie;
cin.get();
cin.get();
return 0;
}

struct CandyBar
{
string brand;
float weight;
int calorie;
};

CandyBar *test=new CandyBar[3];
test[0].brand ="The First";
test[0].weight=5;
test[0].calorie=136;
test[1].brand ="The Second";
test[1].weight=10;
test[1].calorie=350;
test[2].brand="The Third";
test[2].weight=15;
test[2].calorie=333;

#include
#include
using namespace std;
int main()
{
struct CandyBar
{
char *brand;
float weight;
int calorie;
};

CandyBar *test=new CandyBar[3];
test[0].brand =="The First";
test[0].weight=5;
test[0].calorie=136;
test[1].brand =="The Second";
test[1].weight=10;
test[1].calorie=350;
test[2].brand=="The Third";
test[2].weight=15;
test[2].calorie=333;
cout<<"The Brand: "<<test[0].brand;
cout<<", "<<test[1].brand;
cout<<", "<<test[2].brand<<endl;
cout<<endl;
cout<<"The Weight: "<<test[0].weight;
cout<<", "<<test[1].weight;
cout<<", "<<test[2].weight<<endl;
cout<<endl;
cout<<"The Calorie: "<<test[0].calorie;
cout<<", "<<test[1].calorie;
cout<<", "<<test[2].calorie;
cin.get();
cin.get();
return 0;

}

P(x|c)=\frac{P(c|x)\cdot P(x)}{P(x)}


用memcpy给char数组赋值

不懂耶,不过有时候字符串后面不加/0就可能出现乱码。