I tried using this code:
int index = 0;
int value;
int IntegerArray[MAXARRAYSIZE];
while(fscanf(fp, "%d", &value) == 1){
IntegerArray[index++] = value;
}
but I received this error:
Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: KERN_PROTECTION_FAILURE at address: 0x00000038 0x98a7c1ea in __svfscanf_l ()
fp
is of type FILE
and I believe I have used all necessary library inclusions. Please help.
You need to check if index
is less than MAXARRAYSIZE
or not. Otherwise, you will be going out of bounds and invoke undefined behavior (typically invalid memory access).
Change
while(fscanf(fp, "%d", &value) == 1)
to
while((1 == fscanf(fp, "%d", &value)) && (index < MAXARRAYSIZE))
You cannot store integers than you have defined the array size.
you might be exceeding your maxrraysize, as such you are trying to access memory that doesn't belong to your program, so it might be wise to check for that, also please initialize your array just to be safe, since it typically holds what ever previous values where on that location.
int index = 0;
int value;
int IntegerArray[MAXARRAYSIZE] = {0};
while(fscanf(fp, "%d", &value) == 1){
if (index >= MAXARRAYSIZE)
{
printf("reached max array size!\n");
break ;
}
IntegerArray[index++] = value;
}
User contributions licensed under CC BY-SA 3.0