【发布时间】:2011-03-16 14:51:08
【问题描述】:
关于 C 结构体和指针...
昨天我写了以下代码(试着从我的记忆中记住其中的一部分):
typedef struct {
unsigned short int iFrames;
unsigned short int* iTime; // array with elements [0..x] holding the timing for each frame
} Tile;
Tile* loadTile(char* sFile)
{
// expecting to declare enough space for one complete Tile structure, of which the base memory address is stored in the tmpResult pointer
Tile* tmpResult = malloc(sizeof(Tile));
// do things that set values to the Tile entity
// ...
// return the pointer for further use
return tmpResult;
}
void main()
{
// define a tile pointer and set its value to the returned pointer (this should also be allowed in one row)
// Expected to receive the VALUE of the pointer - i.e. the base memory address at where malloc made space available
Tile* tmpTile;
tmpTile = loadTile("tile1.dat");
// get/set elements of the tile
// ...
// free the tile
free(tmpTile);
}
我所看到的:我可以在函数中使用 malloced Tile 结构,但是一旦我尝试在 Main 中访问它,我会从 Visual Studio 收到关于堆的错误(它告诉我在调用后释放了一些东西是返回)。
如果我更改它以便我在 Main 中分配空间,并将指向该空间的指针作为参数传递给 loadTile 函数(以便该函数不再返回任何内容),那么它确实有效,但我相信我也应该能够让 loadTile 函数 malloc 空间并返回指向该空间的指针吧?!
谢谢!!
【问题讨论】:
-
void main... RAAAAARRRRGGGGGHHHHH -
请告诉我们有bug的部分代码