C語言只有在定義字符數組的時候才能用“=”來初始化變量,其它情況下是不能直接用“=”來爲字符數組賦值的,要爲字符數組賦值可以用string.h頭文件中的strcpy函數來完成。
例如:
char a[10] = "123"; /*正確,在定義的時候初始化*/
char a[10];
a = "123"; /*錯誤,不能用“=”直接爲字符數組賦值*/
strcpy(a, "123"); /*正確,使用strcpy函數複製字符串*/
所以要對game[0][0].cpart賦值應該用strcpy(game[0][0].cpart, "123");纔對。
注意要使用strcpy函數要用#include <string.h>包含string.h頭文件。
給C語言結構體中的char數組賦值有兩種方式:
1、在聲明結構體變量時賦值:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
struct stu{
int x;
char name[10];
};
int main(void){
struct stu s={8,"123"};//這樣初始化
printf("%d %s\n",s.x,s.name);
return 0;
}
2、向數組直接拷貝字符串:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
struct stu{
int x;
char name[10];
};
int main(void){
struct stu s;
strcpy(s.name,"abcd");//向name拷貝字符串
s.x=128;
printf("%d %s\n",s.x,s.name);
return 0;
}
有指針成員的結構體賦值
通常情況下,稍微複雜一點的結構體裏面會有指針成員,如果struct中有指針成員,那麼結構體賦值不能簡單的直接複製了,而需要爲指針成員另外分配內存,並將數據拷貝過去
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct MyStruct
{
int a;
int b;
char* c;
};
int main()
{
struct MyStruct t1;
t1.a = 1;
t1.b = 2;
// 爲指針區域賦值
char *p = (char*)malloc(10*sizeof(char));
strcpy(p, "hello");
t1.c = p;
struct MyStruct t2;
// 各個成員分別賦值,可以進行封裝
t2.a = t1.a;
t2.b = t1.b;
char *p2 = (char*)malloc(10*sizeof(char));
strcpy(p2, t1.c);
t2.c = p2;
printf("MyStruct t1: %d, %d, %s\n", t1.a, t1.b, t1.c);
// 釋放了t1的內存
free(p);
printf("MyStruct t2: %d, %d, %s\n", t2.a, t2.b, t2.c);
// 釋放了t2的內存
free(p2);
printf("t1 pointer addr: %p\n", t1.c);
printf("t2 pointer addr: %p\n", t2.c);
return 0;
/*
MyStruct t1: 1, 2, hello
MyStruct t2: 1, 2, hello
t1 pointer addr: 0x6000284d0
t2 pointer addr: 0x600062e10 */
}
參考博客:
https://blog.csdn.net/ginwafts/article/details/80858232
https://blog.csdn.net/chenzhen1080/article/details/83239743