我正在尝试处理有关 C 编程的大学工作表(没有标记,只是为了提高我们的学习水平)。我们要做的是获取有关装运码头的一些详细信息。我决定为此使用结构。
我的代码在下面,我需要帮助的是打印出造船厂位置的信息(以查看其是否正常工作).run。
一切都在编译,根据调试器 shipyard1.run 和 shipyard2.run 指向不同的位置,但我看不到这些值。
int main(int argc, char** argv)
{
typedef struct dockInfo
{
int dockCode;
int dockLength;
}dckDetails;
typdef struct shipyard
{
char dockName[20];
/* however big this number is thats how many dockInfo structs are needed.*/
int numOfDocks;
dckDetails *run; //points to the array of dockInfo structs
};
struct dockInfo *arrayD; // the array to hold all the dockInfo structs
struct dockInfo tempo; // the temporary dockInfo struct to take in the details
struct shipyard shipyard1;
struct shipyard shipyard2;
/**
* the variables for shipyard1 and shipyard2 are then assigned
**/
int i;
for (i=0;i<shipyard1.numOfDocks;i++)
{
arrayD=calloc(shipyard1.numOfDocks,100); // allocate a new bit of memory for arrayD
tempo.dockCode=45*i;
tempo.dockLength=668*i;
arrayD[i]=tempo; //the element of arrayD becomes tempo.
}
shipyard1.run=arrayD; //make shipyard1.run point to the location of arrayD.
for (i=0;i<shipyard2.numOfDocks;i++)
{
arrayD=calloc(shipyard2.numOfDocks,100); // allocate a new bit of memory for arrayD
tempo.dockCode=1234*i;
tempo.dockLength=1200*i;
arrayD[i]=tempo; //the element of arrayD becomes tempo.
}
shipyard2.run=arrayD; //make shipyard2.run point to the new location of arrayD.
int elementTest1; // need element1test to be shipyard1.run[0].dockLength;
int elementTest2; // need element2test to be shipyard2.run[1].dockCode;
return (EXIT_SUCCESS);
}
需要注意的是,因为我还没有写,所以我遗漏了很多代码。目前我使用的是静态示例(shipyard1 和 shipyard2),但将来我将实现“从文件加载信息”功能。
任何帮助将不胜感激,如果我的英语不好,请原谅我的英语,英语不是我的第一语言。
最佳答案
您在 for 循环中有两次 calloc()
。两次您都丢失了返回的地址。
for () {
addr = calloc();
addr[i] = ...
}
第二次循环,你第一次得到的addr
没有了(你自己得到了一个内存泄漏),你在那里保存的值没有了也是。
将 calloc()
移到循环之外...并记住在不再需要时 free()
内存
addr = calloc();
for () {
addr[i] = ...
}
free(addr);
关于c - C 中带有指向其他结构数组指针的结构的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1878115/