[英]Why does the malloc fail?
當編譯器到達函數末尾的賦值時,將發生指針預期錯誤。 為什么?
(從代碼中刪除了強制類型轉換和索引符號;它們在那里是為了“調試”購買的,這顯然使我的問題感到困惑。)
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;
}
int ***array
是一個指向int的指針。
(*array)
是一個指向int的指針。
(*array)[sourceTermIndex]
是一個指向int的指針。
(*array)[sourceTermIndex][driveCurrentIndex]
是一個整數。
(*array)[sourceTermIndex][driveCurrentIndex][preEmphasisIndex]
取消引用int,這是不可能的,因此會出現錯誤消息。
數組要么是不應分配的in參數,要么要使其成為out參數,該參數是指向int指針的指針,因此應使其成為四星指針。
您還可以將malloc強制轉換為int:
(int)malloc(2*sizeof(int)); // pre-emphasis
不這樣做,只會隱藏左手應該是指針的錯誤。 錯誤越早越好; 很少需要強制轉換malloc的結果。
*array
您提供了一個int**
–等效於array[0]
。 因此, (*array)[x]
給你一個int*
而(*array)[x][y]
給你一個簡單的int
。 然后,您嘗試在此int上使用數組索引運算符,並且編譯器會說:“哇,那不是指針!”
我認為您的意思是只寫array
而不是*array
。
(*array)[][][] = ...
有太多的貶低
int ***array
如果您想要一個指向二維數組的指針,則需要
(*array)[][] = ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.