【发布时间】:2017-09-28 12:03:18
【问题描述】:
我有一些代码,它可以工作,但我不明白为什么。这里:
// This structure keeps the array and its bookkeeping details together.
typedef struct {
void** headOfArray;
size_t numberUsed;
size_t currentSize;
} GrowingArray;
// This function malloc()'s an empty array and returns a struct containing it and its bookkeeping details.
GrowingArray createGrowingArray(int startingSize) { ... }
// Self-explanatory
void appendToGrowingArray(GrowingArray* growingArray, void* itemToAppend) { ... }
// This function realloc()'s an array, causing it to double in size.
void growGrowingArray(GrowingArray* arrayToGrow) { ... }
int main(int argc, char* argv[]) {
GrowingArray testArray = createGrowingArray(5);
int* testInteger = (int*) malloc(1);
*testInteger = 4;
int* anotherInteger = (int*) malloc(1);
*anotherInteger = 6;
appendToGrowingArray(&testArray, &testInteger);
appendToGrowingArray(&testArray, &anotherInteger);
printf("%llx\n", **(int**)(testArray.headOfArray[1]));
return 0;
}
到目前为止,一切都按照我的意图进行。让我困惑的部分是这一行:
printf("%llx\n", **(int**)(testArray.headOfArray[1]));
据我了解, printf() 的第二个参数没有意义。我主要是通过反复试验来完成的。它读起来好像我在说结构中指针数组的第二个元素是指向 int 指针的指针。它不是。它只是一个指向 int 的指针。
对我来说有意义的是:
*(int*)(testArray.headOfArray[1])
据我了解,结构中包含的指针数组的第二个元素将由最后一个括号获取,然后我将其转换为指向整数的指针,然后取消引用该指针。
我的理解有什么问题?编译器是如何解释的?
【问题讨论】:
-
你的设计是错误的。
headOfArray应该是void*。你也应该打电话给appendToGrowingArray(&testArray, testInteger);而不是appendToGrowingArray(&testArray, &testInteger); -
*testInteger = 4;写入越界,您只分配了 1 个字节 -
**(int**)(testArray.headOfArray[1])可能是未定义的行为,而且您使用了错误的 printf 格式说明符。为了在发布 MCVE 后获得更好的答案,您未发布的代码中有很多未知因素会影响问题 -
为什么你认为它是一个指向 int 的指针?您已将
&anotherInteger添加到数组中。anotherInteger是指向整数的指针,因此&anotherInteger是指向 int 指针的指针。
标签: c arrays pointers struct casting