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?

RekrowYnapmoc
  • 2,166
  • 2
  • 22
  • 23

2 Answers2

5

*Roomsize[roomIndex] is the same as *(Roomsize[roomIndex]). You want to say (*Roomsize)[roomIndex].

(I'm assuming that Roomsize is actually a int**. If that's not correct, then the problem may lie elsewhere.)

Daniel Gallagher
  • 6,915
  • 25
  • 31
  • The brackets are the normal array access operator. According to the order of operations, array access occurs before pointer dereference. – Daniel Gallagher Jan 31 '11 at 19:07
0

Your first line, when you allocate Roomsize, looks wrong. If I am correct in assuming Roomsize is an int *, you should just say Roomsize = (int *) calloc... As @Daniel posted, your assignment should also be changed to get rid of the asterisk.

EmeryBerger
  • 3,897
  • 18
  • 29
  • No it's fine the way it is I think. (Otherwise I'm assuming it wouldn't get past the compiler). Daniel is correct in his assumption that Roomsize is an int**. It's declared outside the file as an int* and passed in via pointer as I'm going to be writing it.. therefore I'm dereferencing it first. Thanks for the help though. – RekrowYnapmoc Jan 31 '11 at 19:04