代码:
struct bunchofdata
{
int i;
void *dllist[i];
int spltq[i];
pthread_t tlist[i];
};
ERRORMSG:
error: ‘i’ undeclared here (not in a function)
void *dllist[i];
^
我无法理解为什么这不起作用。帮助!
答案 0 :(得分:0)
你可以这样使用,虽然你的结构的每个字段都是数组,但是这样的结构数组可能更好:
#include <malloc.h>
#include <pthread.h>
struct bunchofdata
{
int i;
void** dllist;
int* spltq;
pthread_t* tlist;
};
struct anotherbunchofdata
{
int i;
void* dll;
int spltq;
pthread_t tlist;
};
void init_bunchofdata( int size, struct bunchofdata* bd )
{
bd->i = size;
bd->dllist = malloc( size * sizeof( void* ) );
bd->spltq = malloc( size * sizeof( int ) );
bd->tlist = malloc( size * sizeof( pthread_t ) );
}
void free_bunchofdata( struct bunchofdata* bd )
{
free( bd->dllist );
free( bd->spltq );
free( bd->tlist );
}
int main()
{
struct bunchofdata bd;
init_bunchofdata( 5, &bd );
free_bunchofdata( &bd );
return 0;
}
答案 1 :(得分:0)
除了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;
}