为什么malloc会失败?

tos*_*osa 1 c malloc

当编译器到达函数末尾的赋值时,会发生指针预期错误.为什么?

(从代码中删除了强制转换和索引符号;它们用于"调试"购买显然混乱了我的问题.)

int createArraySimple(int initialResetCount, int ***array)
{
    int sourceTermIndex, driveCurrentIndex, preEmphasisIndex, freqIndex, voltageIndex, slicerIndex, biasIndex;
    int dataIndex, dataCount = 3;

    *array = malloc(2*sizeof(int**));                                       // sourceTerm
    if (*array == NULL)
        return 0;
    for (sourceTermIndex=0; sourceTermIndex < 2; sourceTermIndex++)                 
    {
        *((*array)+sourceTermIndex) = malloc(2*sizeof(int*));                           // drive current
        if (*((*array)+sourceTermIndex) == NULL)
            return 0;
        for (driveCurrentIndex=0; driveCurrentIndex < 2; driveCurrentIndex++)
        {
            *((*((*array)+sourceTermIndex))+driveCurrentIndex = malloc(2*sizeof(int));  // pre-emphasis
            if (*((*((*array)+sourceTermIndex))+driveCurrentIndex) == NULL)
                return 0;
        }
    }

    //'initialize elements in array, since if they are not updated, we won't print them
    for (sourceTermIndex = 0; sourceTermIndex < 2; sourceTermIndex++)
        for (driveCurrentIndex = 0; driveCurrentIndex < 2; driveCurrentIndex++)
            for (preEmphasisIndex = 0; preEmphasisIndex < 2; preEmphasisIndex++)
                *((*((*((*array)+sourceTermIndex))+driveCurrentIndex))+preEmphasisIndex) = initialResetCount;
                        return 1;
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*ham 5

int ***array 是指向指向int的指针的指针.

(*array) 是指向int的指针.

(*array)[sourceTermIndex] 是一个指向int的指针.

(*array)[sourceTermIndex][driveCurrentIndex] 是一个int.

(*array)[sourceTermIndex][driveCurrentIndex][preEmphasisIndex] 是取消引用一个int,这是不可能的,因此错误消息.

这两个数组都是一个不应该赋值的in参数,或者你希望它是一个out参数,它是一个指向指向int的指针的指针,所以把它作为一个四星指针.

你还有一个malloc转换为int:

(int)malloc(2*sizeof(int));    // pre-emphasis
Run Code Online (Sandbox Code Playgroud)

不要这样做,它只会隐藏左手应该是指针的错误.早期错误更好; 对于malloc的结果来说,需要进行铸造是非常罕见的.