簡體   English   中英

當長度直到運行時才知道,如何在C中聲明和初始化這個結構數組?

[英]How to declare and initialize this array of structs in C when the length is not known till runtime?

foo.c的

#include "main.h"
unsigned char currentBar;
struct foo myFoo[getNumBars()];

void initMyFoo(void)
{
 currentBar=(getNumBars()-1);
 for(i=0; i<(sizeof(myFoo)/sizeof(myFoo[0])); i++)
 {
  myFoo[i].we = 1;
  myFoo[i].want = 0;
  myFoo[i].your = 0;
  myFoo[i].soul = 0;
 }
}

main.c中

#include "foo.h"
unsigned char getNumBars()
{
 return getDipSwitchValues();
}
initMyFoo();

(struct foo在foo.h中聲明。)

此代碼必須執行而無需對Bars進行硬編碼,因為Bars的數量將根據用戶設置的DIP開關而變化。 現在我無法初始化myFoo; 我得到錯誤“初始化程序中預期的常量表達式”。 我是否必須將其初始化為:

struct foo myFoo[];

並在以后更改? 如果是這樣,我如何使myFoo []正確長度? 我顯然沒有與所需大小相對應的常量可用。 我是否需要動態分配這個或什么?

我找到了類似的答案,但它對我來說沒什么用處--C ++是一個帶有結構數組的類,不知道我需要多大的數組

struct foo* myFoo;
unsigned int myFooSize;

void initMyFoo(void)
{
  myFooSize = getNumBars();
  myFoo = malloc(myFooSize * sizeof(*myFoo));
  for (i=0; i<myFooSize; i++) {
    /* ... */
  }
}

void cleanupMyFoo(void)
{
  free(myFoo);
  myFoo = NULL;
  myFooSize = 0;
}

1 - 在C99中,您可以使用可變長度數組 ,它允許您創建長度由運行時確定的數組。 您也可以通過編譯器擴展使用它們(GCC支持它們用於非C99 C和C ++),但這不是一個可移植的解決方案。

int someUnknownSize = 0;

/* some code that changes someUnknownSize */

struct foo myFoo[someUnknownSize];

2 - 聲明一個指針,該指針將在運行時使用malloccalloc分配內存。

struct foo *fooPtr = 0; /* null pointer to struct foo */
int sizeToAlloc = 0;
/* determine how much to allocate/modify sizeToAlloc */
fooPtr = malloc(sizeToAlloc * sizeof(*fooPtr));

/* do stuff with the pointer - you can treat it like you would an array using [] notation */
free(fooPtr);

我通常會選擇預期的最大數組大小,如果需要,只需調整大小:

type * a = calloc(sizeof(type),exp_array_size);

並且在將一個新值推送到數組上時(好吧,好吧,我把它視為堆棧...),我檢查它的當前大小與新的:

if (current_size > max_size) {
    max_size *= 2;
    realloc(a,max_size*sizeof(type));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM