无法将结构变量分配给另一个结构变量

Unable to assign structure variable to another structure variable

我无法将一个结构变量 (R2 = R1) 分配给另一个结构变量。请帮助我理解,为什么下面的程序没有被编译,将一个结构变量分配给另一个的最佳方法是什么?

我厌倦了指针方式。仍然没有编译代码...

代码1:

#include<stdio.h>

struct Record
{
    int ID;
    char Name[];
} R1 = {1234, "King"}, R2;

R2 = R1;

int main()
{
    printf("%d   %s \n", R1.ID, R1.Name);
    printf("%d   %s \n", R2.ID, R2.Name);
}

代码2:

#include<stdio.h>

struct Record
{
    int ID;
    char Name[];
} R1 = {1234, "King"}, *R2;

R2 = &R1;

int main()
{

    printf("%d   %s \n", R1.ID, R1.Name);
    printf("%d   %s \n", R2->ID, R2->Name);
}

你可以试试这个。

#include <stdio.h>
#include <string.h>
typedef struct _Record
{
    int ID;
    char Name[10];
} Record;

int main()
{
    Record R1, R2;
    R1.ID = 1234;
    strcpy(R1.Name, "king");
    R2 = R1;
    printf("%d   %s \n",R1.ID,R1.Name);
    printf("%d   %s \n",R2.ID,R2.Name);
}

>>>
1234 king
1234 king

正如@piedar 所说,以下也有效

#include <stdio.h>
#include <string.h>
struct _Record
{
    int ID;
    char *Name;
} R1={1234,"king"}, R2;

int main()
{
    R2 = R1;
    printf("%d   %s \n",R1.ID,R1.Name);
    printf("%d   %s \n",R2.ID,R2.Name);
}

Code1中,不能在C函数外使用R2=R1,否则GCC会报错。只需将 R2=R1; 移动到 main 函数中,然后您的程序将正常运行。

同样,将R2=&R1;移动到main函数中。

您还没有为字符串保留任何 space。在结构末尾 没有大小 的数组称为 flexible array member

struct Record
{
    int ID;
    char Name[];
}

你必须为字符串分配一些内存like this

struct Record R1 = malloc(sizeof(struct Record) + 10 * sizeof(char));

或者将 Name 声明为 char*,然后像平常一样分配内存并复制字符串。用完指针记得删除

或者只是避免使用灵活的数组成员并为 Name

声明固定大小