Set array size at runtime

有些话、适合烂在心里 提交于 2019-12-11 02:13:03

问题


I know how to create a structure array inside a function:

typedef struct item
{
    int test;
};

void func (void) 
{
    int arraysize = 5;
    item ar[arraysize];  
}

But how do I to the same when the array is declared globally:

typedef struct item 
{
    int test; 
};

item ar[];

void func (void)
{
    int arraysize = 5;
    // What to here?
}

回答1:


May be you like this:

typedef struct item 
{
    int test; 
};

item *arr;

void func (void)
{
    int arraysize = 5;
    arr = calloc(arraysize,sizeof(item)); 
     // check if arr!=NULL : allocation fail!
     // do your work 

    free(arr);
}

But its dynamic allocation!

And if arraysize known at compilation time. then better to create a macro like this:

#define arraysize  5

typedef struct item 
{
    int test; 
};

item arr[arraysize];  

side note using upper case for macro constants is good practice




回答2:


Variable length arrays are only allowed in C for arrays with automatic storage duration. Arrays declared at file scope have static storage duration so cannot be variable length arrays.

You can use malloc to dynamically allocate memory for an array object whose size is unknow at compilation time.




回答3:


item * ar:
int count;

void foo()
{
    count = 5;
    ar = malloc(sizeof(item) * count);
    // check to make sure it is not null...
}



回答4:


typedef struct item 
{
    int test; 
};

#define ARRAYSIZE 5

item ar[ARRAYSIZE];



回答5:


You can't modify the size of an array at run time. You can perform a dynamic memory allocation and call realloc() when needed.

EDIT: In your case,I suggest do somethig like this:

item *ar;

    void func(void)
    {
      int arraysize = 5;
      ar = malloc(arsize);
      if(ar) {
      /* do something */
     }
     //don't forget to free(ar) when no longer needed
    }


来源:https://stackoverflow.com/questions/14295786/set-array-size-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!