开发者

Why does the malloc fail?

A pointer expected error occurs when the compiler it gets to the assignment at the at end of the function. Why?

(Removed casts and index notation from code; they were there for "debugging" buy apparently cluttered my question.)

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 == NU开发者_C百科LL)
        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;
}


int ***array is a pointer to pointer to pointer to int.

(*array) is a pointer to pointer to int.

(*array)[sourceTermIndex] is a pointer to int.

(*array)[sourceTermIndex][driveCurrentIndex] is an int.

(*array)[sourceTermIndex][driveCurrentIndex][preEmphasisIndex] is dereferencing an int, which is not possible, hence the error message.

Either array is an in parameter which should not be assigned, or you want it to be an out parameter which is a pointer to a pointer to a pointer to an int, so make it a four star pointer.

You also have a cast of a malloc to int :

(int)malloc(2*sizeof(int));    // pre-emphasis

Don't do that, it will just hide the error that the left hand should have been a pointer. Earlier errors are better; it's very rare for the result of malloc to need to be casted.


*array gets you a int** — it's equivalent to array[0]. So (*array)[x] gives you an int* and (*array)[x][y] gives you a plain int. You then try to use the array index operator on this int and the compiler says, "Whoa, that's not a pointer!"

I think you meant to just write array instead of *array.


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

has one too many levels of derefence for

int ***array

If you want a pointer to a 2d array you need

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜