我試圖從我的用戶得到的數字,這是我的職責,打印動態數組
我的功能得到改編爲指針,將其設置爲一個新的數組並返回,我得到的數量的計數器打印。
,但是當我嘗試打印數組我得到一個錯誤療法被提
int GetNumber(int *arr)
{
int n,i=0;
int *temp;
temp = (int*)calloc(1,sizeof(int));
assert(temp);
scanf("%d",&n);
while(n != -1)
{
i++;
temp = (int*) realloc(temp,i*sizeof(int));
assert(temp);
temp[i-1] = n;
scanf("%d",&n);
}
arr = temp;
return i;
}
您只修改當前堆棧幀上的指針地址,而不是調用的地址。你應該使用'int ** arr'作爲參數並且使用'* arr = realloc(* arr,...)'來重新分配,並且因此將一個指針傳遞給一個int指針,如下所示:'GetNumber(&the_arr)' – Cheatah
而不是'realloc'並將返回值分配給您的原始變量。如果'realloc'失敗,原始的'temp'不會被釋放,並且'NULL'被返回並分配給'temp',導致您失去對'temp'所指向的內存塊的引用,從而產生內存泄漏。而是使用臨時指針,例如'void * t = realloc(temp,i * sizeof * temp);如果(t)temp = t;' –