为什么malloc会失败?

时间:2010-09-22 20:17:41

标签: 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;
}

3 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:2)

*array为您提供int** - 相当于array[0]。因此,(*array)[x]会为您提供int*(*array)[x][y]会为您提供简单的int。然后尝试在这个int上使用数组索引运算符,编译器说:“哇,那不是指针!”

我认为你只想写array而不是*array

答案 2 :(得分:1)

(*array)[][][] = ...

有一个太多的derefence级别

int ***array

如果你想要一个指向二维数组的指针,你需要

(*array)[][] = ...
相关问题