簡體   English   中英

在 C 中,與 malloc 和變量數組聲明相關的兩個給定代碼片段之間有什么區別?

[英]In C, what is the difference between the two given code snippets relating to malloc and variable array declaration?

下面的代碼做完全相同的事情嗎?

代碼片段 1:

#include <stdio.h>
int main(void){
    int size;
    scanf("%d", &size);
    int arr[size];
    //code to manipulate array
    return 0;
}

代碼片段 2:

#include <stdio.h>
int main(void){
    int size;
    scanf("%d", &size);
    int *arr = malloc(size*sizeof(int));
    //code to manipulate array
    free(arr);
    return 0;
}

這些是不一樣的。

第一個片段創建一個具有自動存儲持續時間的數組,即在大多數實現中在堆棧上,而第二個片段在堆上動態創建一個數組。 前者有一個范圍的生命周期而不是封閉它,而后者在程序的生命周期或直到它被釋放之前都是有效的,以先到者為准。

暫無
暫無

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

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