Valhalla Legends Forums Archive | C/C++ Programming | Correct Way of Doing This?

AuthorMessageTime
FrostWraith
I am getting some strange results from the following code:
[code]
while (fgets(buffer, 2048, pfile) != NULL)
{
sscanf(buffer, "%d %d", &stid[i], &stsc[i]);
printf("%d %d\n", stid[i], stsc[i]);
i++;
}[/code]

As you can see, its reading from a file with this type of format:

[code]item1 subitem1
item2 subitem2[/code]

But after the while loop, and I call stsc[0], it contains elements that are supposed to be in stid.  But this only happens AFTER the loop.  During the loop, the output is correct.  I need to use the arrays later on for something else, and with this happening, this isn't possible.  Can anyone see if I'm misusing memory in some way?
April 8, 2008, 5:24 AM
FrOzeN
I've never used an ampersand infront of an array like that so I can't be too sure, but I have a feeling that &stdid[[b][u]i][/b] is being expanded to &*(stid+i) which is treating the value stored in the initial location as the address. I think changing &stdid[[b][u]i][/b] to stid+i should fix the problem (note this also applies to stsc).

Another thing I picked up with that code, you don't really seem to use the i and therefore could change your code to:
[code]while (fgets(buffer, 2048, pfile) != NULL)
{
sscanf(buffer, "%d %d", stid, stsc);
printf("%d\t\t%d\n", stid++, stsc++);
}[/code]
Note that the ++ must come after the variable so it uses the original value of i in the printf() call before it increases it.

I may be wrong though and &array[index] might just do things correctly.

[EDIT] Also, for tabs use \t rather than putting tabs within strings. It makes it easier to distinguish when reading over code.
April 8, 2008, 2:40 PM
FrostWraith
Thanks for your reply.

Well, with &array[index], it still printf's the data correctly to the console inside the loop, but it's like it changes the data when the loop ends.

I also use "i" later on for something else, so i need it to count.

Also thanks on the tab escape sequence, i didn't think about it.

EDIT: Fixed my problem, my arrays were overlapping in memory because I didn't allocate enough space.
April 8, 2008, 10:53 PM

Search