簡體   English   中英

您不能從 function 內部重新分配 C 中的 memory 塊嗎?

[英]Can you not realloc a memory block in C from inside of a function?

因此,在編寫程序時,我意識到當在 main 之外的 function 中使用 realloc 時,如果在 main 中聲明了 memory 的原始塊,它似乎不會將更改保留在 ZC1C425274E68384F1AB50A 之外。 例如

void main()
{

    int *ptr;

    //allocates memory
    ptr = calloc(4, sizeof(int));

    exampleFunction(&ptr);

} //end main


//this function reallocates the memory block of ptr
void exampleFunction(int *ptr)
{

    ptr = realloc(ptr, (sizeof(int) * 10));

} // end exampleFunction

我需要做一些不同的事情還是應該可以正常工作? 此外,這只是示例代碼,並非可運行

額外信息我在 windows 10 上使用 MinGW

您將類型為int **的表達式&ptr傳遞給 function 。

exampleFunction(&ptr);

但是 function 參數的類型為int *

void exampleFunction(int *ptr)

所以 function 聲明及其調用沒有意義。

您必須至少像這樣聲明和定義 function

//this function reallocates the memory block of ptr
void exampleFunction( int **ptr)
{

    *ptr = realloc( *ptr, (sizeof(int) * 10));

}

盡管在調用realloc時使用臨時指針會更好,因為 function 可以返回NULL 在這種情況下, *ptr的原始值將丟失。

所以你應該像這樣聲明 function

//this function reallocates the memory block of ptr
int exampleFunction( int **ptr)
{
    int *tmp = realloc( *ptr, (sizeof(int) * 10));

    int success = tmp != NULL;

    if ( success ) *ptr = tmp;

    return success;

}

你可以這樣寫。

void main()
{

    int *ptr;

    //allocates memory
    ptr = calloc(4, sizeof(int));

   ptr= exampleFunction(ptr);

}

int * exampleFunction(int *ptr)
{
    ptr = realloc(ptr, (sizeof(int) * 10));
  return(ptr);
}

暫無
暫無

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

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