簡體   English   中英

嘗試設置要在C中初始化的struct的內部數組

[英]Trying to set a struct's inside array to be initialized in C

我有這個結構定義:

typedef struct intArray
{
    int myArray[1000];
} intArray;

我的目標是創建一個零的intArray,我試過這個:

intArray example;
int createArray[1000] = {0};
example.myArray = createArray;

這會導致此錯誤消息:

error: assignment to expression with array type

我希望struct自動將數組初始化為0,但我知道這是不可能的,因為它只是一個類型定義而不是變量。 所以我創建了一個並創建了數組,只是嘗試分配它,這就是結果。 任何建議表示贊賞。

聲明像int myArray[1000];這樣的數組int myArray[1000]; 不會讓你改變數組指針的值。 聲明你的結構

typedef struct intArray
{
    int *myArray;
} intArray;

如果你可以的話。

為什么不使用memset將數組歸零? 另外,正如另一個用戶所建議的那樣,最好將這個內存分配給指針....特別是如果你打算在函數之間傳遞這個結構。

只是一個想法,但這將工作:

typedef struct intArray {
    int *myArray;
} intArray;

int main(void)
{
    intArray a;
    int b;

    // malloc() and zero the array
    //         
    // Heh...yeah, always check return value -- thanks,
    // Bob__ - much obliged, sir.
    //              
    if ((a.myArray = calloc(1000, sizeof *a.myArray)) == NULL) {
        perror("malloc()");
        exit(EXIT_FAILURE);
    }

    memset(a.myArray, 0, (1000 * sizeof(int)));

    // Fill the array with some values
    //
    for (b = 0; b < 1000; b++)
        a.myArray[b] = b;

    // Just to make sure all is well...yep, this works.
    //
    for (b = 999; b >= 0; b--)
        fprintf(stdout, "myArray[%i] = %i\n", b, a.myArray[b]);

    free(a.myArray);

}

暫無
暫無

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

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