• Welcome to Valhalla Legends Archive.
 

Correct Way of Doing This?

Started by FrostWraith, April 08, 2008, 12:24 AM

Previous topic - Next topic

FrostWraith

I am getting some strange results from the following code:

while (fgets(buffer, 2048, pfile) != NULL)
{
sscanf(buffer, "%d %d", &stid[i], &stsc[i]);
printf("%d %d\n", stid[i], stsc[i]);
i++;
}


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

item1 subitem1
item2 subitem2


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?

FrOzeN

#1
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[i] is being expanded to &*(stid+i) which is treating the value stored in the initial location as the address. I think changing &stdid[i] 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:
while (fgets(buffer, 2048, pfile) != NULL)
{
sscanf(buffer, "%d %d", stid, stsc);
printf("%d\t\t%d\n", stid++, stsc++);
}

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.
~ FrOzeN

FrostWraith

#2
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.