c - 如何在另一个结构体中初始化一个结构体的数组?

标签 c arrays struct

所以我得到了以下结构:

typedef struct typeData{ 
    char name[20]; 
    double weightIn; 
    double weightOut; 
}dataType;

typedef struct fifoTable{ 
     unsigned short int start; 
     unsigned short int end; 
     dataType data[N]; 
} fifoTable; 

以及以下应该初始化结构的函数:

fifoTable *initFifo(){
    fifoTable table;
    table.start = 0;
    table.start = 0;
    dataType data[N];
    table.data = data;
    return table;
}

我遇到的问题是我收到一条错误消息:“分配给具有数组类型的表达式”。我查了一下,所以我认为不可能在这样的结构内初始化数组。我找到了一些带有 char、int 等数组的示例。但是由于 dataType 结构中还有其他元素,我找不到初始化此表的方法:/我该怎么做?

感谢您的回答。

最佳答案

由于多种原因,这不起作用。

首先,数组不是可赋值的左值。这意味着它不能像您尝试那样出现在作业的左侧。

请注意,初始化(在定义变量时发生)与赋值不同。例如,您可以这样做:

int a[3] = { 3, 4, 5 };

但不是这个:

int a[3] = { 3, 4, 5 };
int b[3];
b = a;

当函数声明返回 fifoTable * 时,您还会从函数返回 fifoTable

您可能想要的是为结构动态分配内存,将其清零,然后返回指针。您可以按如下方式执行此操作:

fifoTable *initFifo(){
    fifoTable *retval = calloc(1, sizeof(fifoTable));
    if (!retval) {
        perror("calloc failed");
        exit(1);
    }
    return retval;
}

关于c - 如何在另一个结构体中初始化一个结构体的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38984201/

相关文章:

c - microblaze 和 vhdl 之间如何通信?

c++ - 使用新标准

python - NumPy 中的引用行为明显不一致

javascript - 我可以将 .map 数组转换为带双引号的逗号分隔数组吗?

c - 结构的大小怎么可能是 4 的非倍数?

c++ - gcc 未声明的标识符 "_asm"

c++ - 替换两个不同数组之间的字符 C++

swift - 如何在 Swift 中创 build 置对象

c# - 将带有 char* 的结构编码到 C#

c - 通过 C 中的 printf 函数处理 %s