使用 calloc 后发生 C 访问冲突
注:C 是 Microsoft C 编译器。
我在使用以下代码时遇到问题。
*Roomsize = (int*)calloc(sizeof(int),sched->numberOfRooms);
roomIndex = 0;
for(roomIndex=0; roomIndex< sched->numberOfRooms; roomIndex++)
{
fscanf(inputFile,"%d",&lineInput);
numberOfLinesRead++;
*Roomsize[roomIndex] = lineInput;
}
这是在一个单独的 C 文件中。直到我决定将事物分开以使它们更易于维护之前,我才遇到这个问题,我认为我只是与指针有点混淆了。
calloc 工作正常。
在循环的第一次迭代中, roomIndex 的元素零被正确设置。
然而,循环中的第二个元素(元素 1)始终会导致运行时访问冲突。
我后来在使用二维数组的代码中也遇到了这个问题,但我认为这是完全相同的问题,这只是最简单的情况。
谁能帮助我理解为什么除了第一个元素之外似乎不可能设置任何内容?
Note: C is Microsoft C Compiler.
I'm having trouble with the following code.
*Roomsize = (int*)calloc(sizeof(int),sched->numberOfRooms);
roomIndex = 0;
for(roomIndex=0; roomIndex< sched->numberOfRooms; roomIndex++)
{
fscanf(inputFile,"%d",&lineInput);
numberOfLinesRead++;
*Roomsize[roomIndex] = lineInput;
}
This is in a separate C file. I wasn't having this problem until I decided to separate things out to make them more maintainable and I think I'm just getting a little mixed up with pointers.
The calloc works fine.
On the first iteration of the loop, element zero of roomIndex gets set properly.
However the second element (element 1) in the loop, always results in an access violation at runtime.
I run into this problem later in my code too with a 2d array, but I'm figuring it's the exact same problem and this is just the most simple case.
Can anyone help me understand why it seems impossible to set anything but the first element here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
*Roomsize[roomIndex]
与*(Roomsize[roomIndex])
相同。您想说(*Roomsize)[roomIndex]
。(我假设
Roomsize
实际上是一个int**
。如果这不正确,那么问题可能出在其他地方。)*Roomsize[roomIndex]
is the same as*(Roomsize[roomIndex])
. You want to say(*Roomsize)[roomIndex]
.(I'm assuming that
Roomsize
is actually aint**
. If that's not correct, then the problem may lie elsewhere.)当您分配 Roomsize 时,您的第一行看起来是错误的。如果我正确地假设 Roomsize 是
int *
,你应该只说Roomsize = (int *) calloc...
正如 @Daniel 发布的那样,你的作业也应该是更改以摆脱星号。Your first line, when you allocate
Roomsize
, looks wrong. If I am correct in assuming Roomsize is anint *
, you should just sayRoomsize = (int *) calloc...
As @Daniel posted, your assignment should also be changed to get rid of the asterisk.