c - 得到 "error: undeclared here (not in a function)"和 void * 变量数组

标签 c

代码:

struct bunchofdata
{
    int i;
    void *dllist[i];
    int spltq[i];
    pthread_t tlist[i];
};

错误消息:

error: ‘i’ undeclared here (not in a function)
  void *dllist[i];
               ^

我不明白为什么这不起作用。

最佳答案

除了 pikkewyn's answer ,实现此目的的另一种方法是使用 Flexible Array Member

这比单独分配成员更容易管理。

#include <stdio.h>
#include <stdlib.h>
typedef int pthread_t;
struct data
{
    void *dl;
    int spltq;
    pthread_t thread;
};
struct bunchofdata
{
    int i;
    struct data data_list[];
};
struct bunchofdata * data_factory(int size)
{
    struct bunchofdata * ret = malloc(sizeof(struct bunchofdata)
                                      +size*sizeof(struct data));
    /* fill in the members here*/
    ret->i=size;
    return ret;
}
int main(void) {
    struct bunchofdata *data10=data_factory(10);
    data10->data_list[9].spltq=0;
    printf("data10->data_list[9].spltq=%d",data10->data_list[9].spltq);
    free(data10)
    return 0;
}

关于c - 得到 "error: undeclared here (not in a function)"和 void * 变量数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35687137/

相关文章:

用于粘贴标记的 C 宏

c - 如何只包含来自不同 C 文件的一个函数

c++ - 检查是否可以删除驱动器

c - 如何在不使用 C 中的内置函数和循环的情况下打印字符串的反转?

c++ - 无法使用 typedef 结构解析字段 'tile'

c - 有什么理由我不应该对 C 中的所有变量和函数声明使用 "volatile"关键字?

c - 就 cpu 而言,coSTLy 如何成为低争用互斥体

c - 如何使用 C.dll

c - 具有作用域和全局变量的 Malloc

c - 释放一个结构......我不确定我做得是否正确