簡體   English   中英

function scope外的動態分配

[英]Dynamic allocation outside the scope of a function

如果我想創建一個用作全局變量的數組,以防萬一我已經知道大小我可以這樣做:

#include <stdio.h>
#include <stdlib.h>

int array[]={1,1,1,1};

int main()
{
    printf("%d", array[0]);
}

但是,這不適用於malloc 確實,下面的代碼

#include <stdio.h>
#include <stdlib.h>

int* array=malloc(4*sizeof(int));

int main()
{
    printf("%d", array[0]);
}

將返回一個錯誤( error: initializer element is not constant )。 但是,如果我嘗試在 function 的 scope 內部執行相同操作,則沒有問題。

我相信關於動態分配的工作原理,我肯定缺少一些東西。

到底是怎么回事? 如何在任何 function 的 scope 之外動態定義一個數組並將它們用作全局變量?

在 C 語言中,代碼只能在 function 主體中執行。

當您嘗試在malloc之外調用 malloc 時,第二個代碼無效。

在 C 中使用全局變量被認為是一種不好的做法,因此如果不是 100% 必要,請盡量避免使用它。

如果你想要一個全局指針:

int *array;

int main(void)
{
     array = malloc(100);
     /* .... */
}

一些編譯器支持非標准擴展。 例如,在 GCC 中,您可以使用該屬性在調用 function main之前執行代碼

int* array;

void __attribute__((constructor)) aray_const(void)
{
    array = malloc(4 *sizeof(*array));
    if(array) memcpy(array, (int[]){1,2,3,4}, 4 * sizeof(*array));
}

int main()
{
    printf("%d %d %d %d\n", array[0], array[1], array[2], array[3]);
     /* .... */
}

https://godbolt.org/z/bz4YjzfK5

在 C 中,存儲持續時間為 static 的對象可以通過常量表達式進行初始化。 並且在文件 scope 中的第二個程序中聲明的指針array與文件 scope 中聲明的任何 object 具有 static 存儲持續時間。

來自C標准(6.7.9初始化)

4 具有 static 或線程存儲持續時間的 object 的初始化程序中的所有表達式應為常量表達式或字符串文字。

此外,function malloc分配未初始化的 memory。因此調用 printf

printf("%d", array[0]);

在任何情況下都可以調用未定義的行為。

您可以使用 main 中的賦值運算符按以下方式重寫您的程序

#include <stdio.h>
#include <stdlib.h>

int *array;

int main( void )
{
    size_t n = 4;
    array = malloc( n * sizeof( int ) );

    if ( array != NULL )
    {
        int value = 1;
        for ( size_t i = 0; i < n; i++ )
        {
            array[i] = value++;
        }

        for ( size_t i = 0; i < n; i++ )
        {   
            printf( "%d ", array[i] );
        }
        putchar( '\n' );
    }

    free( array );
}

或者您可以使用 function calloc而不是malloc 在這種情況下,分配的 memory 將被零初始化。

#include <stdio.h>
#include <stdlib.h>

int *array;

int main( void )
{
    size_t n = 4;
    array = calloc( n, sizeof( int ) );

    if ( array != NULL )
    {
        for ( size_t i = 0; i < n; i++ )
        {   
            printf( "%d ", array[i] );
        }
        putchar( '\n' );
    }

    free( array );
}

請注意,當不再需要時,您應該始終釋放分配的 memory。

暫無
暫無

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

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