解決該問題的方法:使用strcpy函數進行字符串拷貝
原型聲明:char *strcpy(char* dest, const char *src);
頭文件:#include <
string.h> 和 #include <stdio.h>
功能:把從src地址開始且含有NULL結束符的字符串復制到以dest開始的
地址空間
說明:src和dest所指內存區域不可以重疊且dest必須有足夠的空間來容納src的字符串。
返回指向dest的
指針。
1 // testArray.cpp : 定義控制台應用程序的入口點。 2 3 #include "stdafx.h" 4 #include "string.h" 5 6 #define MAX_AGE_SIZE 120 7 #define MAX_NAME_SIZE 100 8 9 typedef enum{//枚舉值定義 10 walking = 1, 11 running = 2, 12 swimming = 3, 13 jumpping = 4, 14 sleeping = 5 15 }Hobby; 16 17 typedef enum{ 18 Chinese = 1, 19 English = 2, 20 Japanese = 3 21 }Language; 22 23 typedef struct People{//結構體定義 24 union{//聯合體定義,使用方法和struct類似 25 struct{ 26 char age[MAX_AGE_SIZE]; 27 char name[MAX_NAME_SIZE]; 28 }Child; 29 Hobby hobby; 30 Language language; 31 }Student; 32 }People; 33 34 35 int _tmain(int argc, _TCHAR* argv[]) 36 { 37 char name1[MAX_NAME_SIZE] = {"test1"}; 38 char name2[MAX_NAME_SIZE] = {"test2"}; 39 40 People p[2]; 41 //p[0].Student.Child.age = "10";//報錯:表達式必須是可修改的左值(原因:字符串不能直接賦值 ) 42 strcpy(p[0].Student.Child.age,"10");//使用strcpy函數實現字符串拷貝 43 strcpy(p[0].Student.Child.name,name1); 44 p[0].Student.hobby = walking; 45 p[0].Student.language = Chinese; 46 47 strcpy(p[1].Student.Child.age,"12"); 48 strcpy(p[1].Student.Child.name,name2); 49 p[1].Student.hobby = running; 50 p[1].Student.language = English; 51 52 printf("Student1's name:%s\n",p[0].Student.Child.name); 53 return 0; 54 }