结构体中的成员如果是字符数组,有几种赋值方式?
展开全部
1、声明结构体变量时用字符串常量初始化
2、用scanf的%s输入结构体变量的字符数组成员
3、用strcpy给结构体变量的字符数组成员复制进内容
2、用scanf的%s输入结构体变量的字符数组成员
3、用strcpy给结构体变量的字符数组成员复制进内容
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
// 2013-04-02-001.cpp : 定义控制台应用程序的入口点。//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
typedef struct test
{
string strname;
int nid;
int age;
char sex[10];
unsigned int sn: 4;
} test_a,test_b[2];
typedef struct test2
{
string strname;
int nid;
int age;
char sex[5];
unsigned int sn: 4;
} test_a2;
union best
{
int number;
char name[10];
double value;
}pbest;
int _tmain(int argc, _TCHAR* argv[])
{
test_a *ptest=new test_a;
ptest->strname="中国人";
ptest->nid=300;
cout<<"test_a.name= "<<ptest->strname<<"\n"<<"test_a.nid= "<<ptest->nid<<endl;
test test_b[2]={
{"wj",18,30,"man"},
{"jack",28,40,"woman",88},
};
//test2 testa2={"kfc",28,40,"woman",88};
test2 testa2;
testa2.strname="kfc";
testa2.age=28;
testa2.nid=40;
strcpy(testa2.sex,"woman");//值超出数组范围
testa2.sn=2231;
cout<<"test_b.name= "<<test_b[0].strname<<endl;
cout<<"testa2.name= "<<testa2.strname<<endl;
cout<<"testa2.sex= "<<testa2.sex<<endl;
cout<<"testa2.sn= "<<testa2.sn<<endl;
pbest.number=30;//分别赋值
cout<<"pbest.number= "<<pbest.number<<endl;//分别输出
pbest.value=800;
cout<<"pbest.value= "<<pbest.value<<endl;
strcpy(pbest.name,"新中国");
cout<<"pbest.name= "<<pbest.name<<endl;
//best pbest={50,800,strcpy(pbest.name,"新中国")};
system("pause");
return 0;
}
这样输出的原因:结构体里面的每一个元素都占有一定的内存空间。而共用体占用其元素中最长的变量的那个类型的内存空间。其赋值是覆盖式的
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
typedef struct test
{
string strname;
int nid;
int age;
char sex[10];
unsigned int sn: 4;
} test_a,test_b[2];
typedef struct test2
{
string strname;
int nid;
int age;
char sex[5];
unsigned int sn: 4;
} test_a2;
union best
{
int number;
char name[10];
double value;
}pbest;
int _tmain(int argc, _TCHAR* argv[])
{
test_a *ptest=new test_a;
ptest->strname="中国人";
ptest->nid=300;
cout<<"test_a.name= "<<ptest->strname<<"\n"<<"test_a.nid= "<<ptest->nid<<endl;
test test_b[2]={
{"wj",18,30,"man"},
{"jack",28,40,"woman",88},
};
//test2 testa2={"kfc",28,40,"woman",88};
test2 testa2;
testa2.strname="kfc";
testa2.age=28;
testa2.nid=40;
strcpy(testa2.sex,"woman");//值超出数组范围
testa2.sn=2231;
cout<<"test_b.name= "<<test_b[0].strname<<endl;
cout<<"testa2.name= "<<testa2.strname<<endl;
cout<<"testa2.sex= "<<testa2.sex<<endl;
cout<<"testa2.sn= "<<testa2.sn<<endl;
pbest.number=30;//分别赋值
cout<<"pbest.number= "<<pbest.number<<endl;//分别输出
pbest.value=800;
cout<<"pbest.value= "<<pbest.value<<endl;
strcpy(pbest.name,"新中国");
cout<<"pbest.name= "<<pbest.name<<endl;
//best pbest={50,800,strcpy(pbest.name,"新中国")};
system("pause");
return 0;
}
这样输出的原因:结构体里面的每一个元素都占有一定的内存空间。而共用体占用其元素中最长的变量的那个类型的内存空间。其赋值是覆盖式的
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询