I'd be careful with the <=, and I wish I'd spent more time looking into the 'Why doesn't this work?', but you may want to try something like this.
#include <stdio.h>
size_t FillAgeList(int ageList[], size_t size)
{
size_t i, counter = 0;
/* Reads the data from .dat file */
for ( i = 0; i < size; ++i )
{
if ( scanf("%d", &ageList[i]) != 1 || ageList[i] == 0 )
{
break;
}
++counter;
}
/* Prints the integers */
for ( i = 0; i < counter; ++i )
{
printf("%d\n", ageList[i]);
}
return counter;
}
int main(void)
{
int array[10];
size_t size = FillAgeList(array, sizeof array / sizeof *array);
printf("size = %d\n", (int)size);
return 0;
}
[edit]Oh, wait. I think this is it.
for(i = 0; i <= MAX || ageList[i] != 0; i++)
You incrementi past any known values and then check to see whether this is a zero, when you've already initialized it to -1 (if you havent' wandered off the end of the array). So this might also cure things.
#include <stdio.h>
#define MAX 10
int FillAgeList(int ageList[])
{
int i;
int counter;
/*Initializes the array*/
for(i = 0; i <= MAX; i++)
{
ageList[i] = -1;
}
counter = 0;
/*Reads the data from .dat file*/
for(i = 0; i <= MAX; i++)
{
scanf("%d",&ageList[i]);
if(ageList[i] == 0)
{
break;
}
counter += 1;
}
/*Prints the integers*/
for(i = 0; i <= MAX && ageList[i] != 0;i++)
{
printf("%d\n",ageList[i]);
}
return(counter);
}
int main(void)
{
int array [ MAX + 1 ], size = FillAgeList(array);
printf("size = %d\n", size);
return 0;
} Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314