This is my first post here. I am making a program in C that handles Joker results (it's a game like Powerball). Below I include only the code that matters for my question. First, you input 1 to the program so that it reads the previous results file. I will include the file so that you can run it as well.Afterwards you input 3 so that you insert a result in the form of
id;day/month/year;num1;num2;num3;num4;num5;joker
After that you input 99 and you see the full result array.
The problem is that the first 2 results that are appended to the array(resArr)
are displayed properly, but all the following appends are stored with pseudorandom numbers. Any clue why my code works only for 2 repetitions?
The file: link
#include <stdio.h>
#include <stdlib.h>
typedef struct results
{
int id,date[3],num[5],joker;
}Results;
Results *read()
{
FILE *fp=fopen("joker.csv","r");
Results *temp=(Results *)malloc(sizeof(Results));
Results *result=(Results *)malloc(sizeof(Results));
int i=0,size=1;
while(!feof(fp))
{
char *s=(char *)malloc(50*sizeof(char));
fgets(s,50,fp);
sscanf(s,"%d;%d/%d/%d;%d;%d;%d;%d;%d;%d",&result[i].id,&result[i].date[0],&result[i].date[1],&result[i].date[2],&result[i].num[0],&result[i].num[1],&result[i].num[2],&result[i].num[3],&result[i].num[4],&result[i].joker);
temp=(Results *)realloc(result,(++size)*sizeof(Results));
if (temp) result=temp;
else
{
result=NULL;
break;
}
i++;
}
fclose(fp);
return result;
}
int findLength()
{
FILE *fp=fopen("joker.csv","r");
int len,i=0;
while(!feof(fp))
{
char *s=(char *)malloc(50*sizeof(char));
fgets(s,50,fp);
i++;
}
fclose(fp);
len=i-1;
return len;
}
void eisagogi(Results *resArr,int *len)
{
Results result;
printf("id;dd/mm/yyyy;num1;num2;num3;num4;num5;joker\n");
scanf("%d;%d/%d/%d;%d;%d;%d;%d;%d;%d",&result.id,&result.date[0],&result.date[1],&result.date[2],&result.num[0],&result.num[1],&result.num[2],&result.num[3],&result.num[4],&result.joker);
resArr=(Results *)realloc(resArr,(*len+1)*sizeof(Results));
resArr[*len]=result;
*len=*len+1;
}
void showResults(Results *resArr,int len)
{
int i;
for (i=0;i<len;i++)
{ printf("%d;%d/%d/%d;%d;%d;%d;%d;%d;%d\n",resArr[i].id,resArr[i].date[0],resArr[i].date[1],resArr[i].date[2],resArr[i].num[0],resArr[i].num[1],resArr[i].num[2],resArr[i].num[3],resArr[i].num[4],resArr[i].joker);
}
}
int menuChoose()
{
int choice;
printf("Load results 1\n");
printf("Append result 3\n");
printf("Result array 99\n");
printf("Exit 0\n");
scanf("%d",&choice);
return choice;
}
int main()
{
Results *resArr=(Results *)malloc(sizeof(Results));
int choice,len;
while(1)
{
choice=menuChoose();
switch(choice)
{
case 1:
resArr=read();
len=findLength();
break;
case 3:
eisagogi(resArr,&len);
break;
case 99:
showResults(resArr,len);
break;
case 0:
exit(0);
break;
}
}
return 0;
}