结构体数组赋值的问题

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 "stdafx.h"//If the vc++6.0, with this line.
#include "stdio.h"
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 "stdafx.h"//If the vc++6.0, with this line.
#include "stdio.h"
#include "string.h"
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;
}

至于为什么不能直接给字符数组赋值字符串呢?网上各大神说的是,因为在初始化字符数组时,数组的内存地址已经确定,不能再做修改。

想要直接给数组赋值字符串除了在初始化时赋值,还可以通过两个函数,void *memcpy(void*dest, const void *src, size_t n);,strcpy(str1,str2)。

个人的理解是:在初始化字符数组时,编译器会给字符数组首元素赋予初始地址。而后再另外给字符数组赋值字符串,此时字符数组已经具有地址,编译器就会以为是你要给字符数组某个元素赋值。所以说此时是可以给单个字符数组元素赋值单个字符的,但是不可以赋值字符串。

猜你喜欢

转载自blog.csdn.net/ginwafts/article/details/80858232