我想有一個函數,分配一個複雜的雙數組,執行一些操作,並返回計算出的最後一個值。雖然計算很好,但我在嘗試釋放分配的空間時遇到了問題。在執行過程中,我得到了「雙重釋放或內存損壞」的錯誤。我正在使用標準庫。使用免費()與動態分配的複雜指針
這裏是我的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <complex.h>
#include <assert.h>
double complex main()
{
// Declare fixed number of steps.
int number_of_elements=10;
// Reserve memory for array.
double complex *complexArray = calloc(number_of_elements,sizeof(double complex));
// Verify if allocation was successfull.
assert(complexArray!=NULL);
// Fill first position with number and start counting
complexArray[0]=1+2*I;
int i=0;
for (i=0;i<number_of_elements;i++)
{
complexArray[i+1]=2*complexArray[i]; // Simple operation
printf("The complex number stored in position %i is %f+i%f\n\n",i+1,creal(complexArray[i+1]),cimag(complexArray[i+1])); // Print the current number
}
double complex output=complexArray[i];
assert(complexArray!=NULL); // Check if pointer is not NULL again
free(complexArray); // Program fails here
complexArray=NULL;
return output;
}
我從「雙情結」改變了數據類型「雙」和它的作品。有什麼方法可以釋放複雜的數組嗎?