簡體   English   中英

在C中動態分配內存時出錯

[英]Error in dynamically allocating memory in C

我正在嘗試計算NxN矩陣的行列式。 這段代碼在嘗試動態分配內存的行中給出了錯誤。

錯誤:無法將類型為“ int”的值分配給類型為“ float *”的實體

錯誤:無法將類型為“ int”的值分配給類型為“ float **”的實體

double CalcDeterminant( float **mat, int order)
{
    float **minor;
    unsigned short i;
    float det = 0;
    // order must be >= 0
    // stop the recursion when matrix is a single element
    if( order == 1 )
        return mat[0][0];

    // the determinant value
    // allocate the cofactor matrix

    **minor = malloc((order-1) * sizeof(float *));
    for(i=0;i<order-1;i++)
        minor[i] = malloc((order-1) * sizeof(float));**

    //float *mat2d = malloc( rows * cols * sizeof( float ));
    for(i = 0; i < order; i++ )
    {
        // get minor of element (0,i)
        GetMinor( mat, minor, 0, i , order);
        // the recusion is here!

        det += (i%2==1?-1.0:1.0) * mat[0][i] * CalcDeterminant(minor,order-1);
        //det += pow( -1.0, i ) * mat[0][i] * CalcDeterminant( minor,order-1 );
    }

    // release memory
    for(i=0;i<order-1;i++)
        free(minor[i]);
    free(minor);
    return det;
}

您需要添加#include <stdlib.h>以便正確聲明malloc()

就目前而言,編譯器非常寬松(C89模式),並且允許隱式函數聲明,因此,當編譯器遇到malloc() ,它將假定它是一個返回int的函數,而不是正確的void *

您需要更改編譯選項,直到編譯器發出更大的抱怨為止。 例如,如果您使用GCC,則應考慮:

gcc -std=c99 -Wall -Wextra -Wstrict-prototypes -Wmissing-prototypes ...

您可能更喜歡甚至需要使用-std=gnu99而不是-std=c99 可以在仍使用C99核心語言的情況下啟用許多擴展。 但是,按照這些原則使用選項並確保沒有編譯警告是很好的紀律。 使用-Werror加強訓練; 它將來自編譯器的所有警告消息轉換為錯誤,因此編譯失敗。

您需要包括頭文件stdlib.h

暫無
暫無

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

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