当前位置: 动力学知识库 > 问答 > 编程问答 >

c - got "error: undeclared here (not in a function)" with void * variable array

问题描述:

codes:

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];

^

I can't understand why this isn't work. help!

网友答案:

In addition to pikkewyn's answer, another way to implement this is to use Flexible Array Member

This makes it easier to manage than allocating members separately.

#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;
}
网友答案:

You can use sth like this, although since each field of your structure is array it might be nicer to have array of such structs:

#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;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: