call dynamic c array values - c

I am trying to access all values that I call. I'm not sure if I use array values correctly. In code below I'm trying to write values in file to memory and then call them by address. what is the problem? Am I overwriting on same memory adresses or I call them wrongly? Any help please?
my text file:
0 0 100 500 player1
0 1 400 450 player2
1 1 300 600 player3
FILE *fp;
struct ob {
int x;
int y;
int c_hp;
int max_hp;
char name[100];
int p_id;
};
struct ob *ptr;
int count = 0;
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: program <File name>\n");
exit(1);
}
read_player_values();
}
void read_player_values() {
ptr = (struct ob *)malloc(sizeof(struct ob));
if (ptr == NULL)
printf("out of memory");
else {
while (!feof(fp)) {
count++;
fscanf(fp, "%d%d%d%d%s", &ptr->x, &ptr->y, &ptr->c_hp, &ptr->max_hp,
ptr->name, &ptr->p_id);
ptr->p_id = count;
printf("%d %d %d %d %s %d", ptr->x, ptr->y, ptr->c_hp, ptr->max_hp,
ptr->name, ptr->p_id);
printf("\n");
}
fclose(fp);
printf("------\n");
for (int i = 0; i < count; i++) {
/* here is my problem */
/*trying to print all player names here*/
printf("%s\n", (ptr - i)->name);
}
}
}

Firstly, you have to open the file in main function:
fp = fopen(argv[1],"r");
if (!fp)
return -1;
You can use fgets function to get each line of the file and get all values from this line by using sscanf. After each iteration, you have to re-allocate for ptr. ptr here likes an array that has count elements.
char line_buf[256];
count = 1;
while (fgets(line_buf, sizeof(line_buf), fp)) {
ptr = realloc(ptr, count * sizeof(struct ob));
if(!ptr)
return;
sscanf(line_buf, "%d%d%d%d%s\n", &ptr[count-1].x, &ptr[count-1].y, &ptr[count-1].c_hp, &ptr[count-1].max_hp,
ptr[count-1].name);
ptr[count-1].p_id = count;
printf("%d %d %d %d %s %d", ptr[count-1].x, ptr[count-1].y, ptr[count-1].c_hp, ptr[count-1].max_hp,
ptr[count-1].name, ptr[count-1].p_id);
printf("\n");
count++;
}
For printing all names:
printf("------\n");
for (int i = 0; i < count-1; i++) {
printf("%s\n", ptr[i].name);
}
the result after testing:
#cat text.txt
0 0 100 500 player1
0 1 400 450 player2
1 1 300 600 player3
./test text.txt
0 0 100 500 player1 1
0 1 400 450 player2 2
1 1 300 600 player3 3
------
player1
player2
player3

Related

Selection sort not working as expected (C language)

I have to sort an array of structs with selection sort, after I read them from a file.txt.
My algorithm is not working as expected, but it always avoid to sort them and it print the struct in decreasing order.
Example of file.txt :
P0 "ANTONIO" 2000 4
P1 "BARTOLOMEO" 1995 6
P2 "CARLO" 2020 1
P3 "DEMETRIO" 1960 2
P4 "ETTORE" 1920 3
P5 "FRANCESCO" 1950 5
Input: 2 5 3 1 6 4
Output: 4 6 1 3 5 2
What am I doing wrong?
Code below:
#include <stdio.h>
#include <stdlib.h>
#define N 7
struct persona
{
char codice[10];
char nome[30];
int anno[10];
int reddito[10];
};
int main()
{
FILE* fp;
fp = fopen("Testo.txt", "r");
struct persona* persona = malloc(sizeof(struct persona) * N);
int i = 0;
int j = 0;
if (fp != NULL)
{
while (i < N-1)
{
fscanf(fp, "%s %s %s %s",
persona[i].codice,
persona[i].nome,
persona[i].anno,
persona[i].reddito);
i++;
}
}
else
{
perror("Errore");
}
fclose(fp);
for(i=0; i<N-2; i++)
{
int min = persona[i].reddito;
for(j=i+1; j<N-1; j++)
{
if(persona[j].reddito < persona[i].reddito)
{
min = persona[j].reddito;
}
persona[N] = persona[j];
persona[j] = persona[i];
persona[i] = persona[N];
}
}
for(i=0; i<N-1;i++)
{
printf("%s\t %s\t %s\t %s\n",
persona[i].codice,
persona[i].nome,
persona[i].anno,
persona[i].reddito);
}
}
You have 6 lines in the file, but you have defined N as 7. It should be updated to 6.
while (i < N-1)
You are reading the first N-2, that is, 5 lines from the file. The 6th line is not being read. Same goes for other loops in the code using N.
int anno[10];
int reddito[10];
You do not need integer array to read the numeric fields in file, an integer should suffice.
As mentioned by #WhozCraig in the comments, the selection sort algorithm is incorrect. Here's the updated code for reference:
#include <stdio.h>
#include <stdlib.h>
#define N 6
typedef struct persona
{
char codice[10];
char nome[30];
int anno;
int reddito;
} PERSONA;
int main()
{
FILE *fp;
if ((fp = fopen("file.txt", "r")) == NULL)
{
perror("\nFile not found");
exit(1);
}
PERSONA *persona = malloc(sizeof(struct persona) * N);
int i = 0, j;
while (i < N)
{ if (fscanf(fp, "%s %s %d %d", persona[i].codice, persona[i].nome, &persona[i].anno, &persona[i].reddito) == EOF) {
break;
}
i++;
}
fclose(fp);
PERSONA temp;
/* selection sort */
for (i = 0; i < N - 1; i++)
{
int jMin = persona[i].reddito;
for (j = i + 1; j < N; j++)
{
if (persona[j].reddito < persona[jMin].reddito)
{
jMin = j;
}
}
if (jMin != i)
{
temp = persona[i];
persona[i] = persona[jMin];
persona[jMin] = temp;
}
}
for (i = 0; i < N; i++)
{
printf("\n%s\t %s\t %d\t %d", persona[i].codice, persona[i].nome, persona[i].anno, persona[i].reddito);
}
}
Further improvements:
You could also calculate the number of lines in the file in the code instead of relying on a hardcoded value N.
The statement to check sets only the min only if this statement is true
if(persona[j].reddito < persona[i].reddito)
try using the qsort function
int cmpfunc (const void * a, const void * b) {
struct persona *p1 = (struct persona *)a;
struct persona *p2 = (struct persona *)b;
if(p1->reddito < p2->reddito) return -1;
if(p1->reddito > p2->reddito) return 1;
return 0;
}
and instead of the for loop, use
qsort(persona, N, sizeof(struct persona), cmpfunc);

Reading In PPM Pixels As RGB Integers

So my code involves reading in a PPM image and then storing it in an array so it can be saved in an new ppm file. Though I think there is a problem with my pointers that means its not actually reading the file. Also my code ends after allocating the memory for the array. Any help is much appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxheight 1080
#define maxwidth 1920
#define RGB_COMPONENT_COLOUR 255
#define pgmtype "P2"
#define ppmtype "P3"
typedef struct
{
int red, green, blue;
} PPMPixel;
typedef struct
{
int x, y;
} PPMImage;
typedef struct
{
int rgb_comp_colour;
char filetype[3];
int height;
int width;
} PPMHead;
/*PPMHead head[3];
{
head[3].filetype;
head[3].height;
head[3].width;
}*/
PPMHead head;
PPMHead* head_ptr = &head;
PPMPixel p;
PPMPixel* p_ptr = &p;
PPMPixel *data; //Defines pointer to PPMPixel
int **Array; //Double pointer defines as a pointer pointing to a pointer that is pointing to an integer
PPMPixel **RGBArray; //Double pointer defines as a pointer pointing to a pointer that is pointing to the PPMPixel structure
FILE *fp;
int r, g, b;
void headercheck ()
{
fscanf(fp, "%s %d %d %d", head.filetype, &head.width, &head.height, &head.rgb_comp_colour);
printf("%s %d %d %d", head.filetype, head.width, head.height, head.rgb_comp_colour);
if (head.width > maxwidth || head.height > maxheight)
{
printf("\tInvalid image size. The maximum value of image is 1920x1080.\n");
printf("\tImage size is %d x %d\n", head.width, head.height);
}
else
{
printf("\tImage size is valid\n");
printf("\tImage size is %d x %d\n", head.width, head.height);
}
if ((strcmp (head.filetype, pgmtype)!=0) && (strcmp (head.filetype, ppmtype)!=0))
{
printf("\tInvalid filetype\n");
}
else
{
if(strcmp (head.filetype, pgmtype)==0)
{
printf("\t File is PGM type image\n");
}
else
{
if(strcmp (head.filetype, ppmtype)==0)
{
printf("\t File is PPM type image\n");
}
}
}
if ((head.rgb_comp_colour == RGB_COMPONENT_COLOUR))
{
printf("\t Image is 8 bit\n");
}
else
{
if (head.rgb_comp_colour > RGB_COMPONENT_COLOUR)
{
printf("Maximum bit-depth is 8 bits\n");
}
else
{
printf("\tImage is not 8 bit\n");
}
}
}
int main(void)
{
char fname[100];
printf("Enter file name: ");
scanf("%s", fname);
fseek(stdin,0,SEEK_END);
fp = fopen(fname, "r");
if (fp == NULL)
{
printf("\tError while opening the file\n");
}
else
{
printf("\tReading in %s\n", fname);
}
headercheck();
if (strcmp (head.filetype, ppmtype)==0)
{
RGBArray = (PPMPixel **)malloc(head.height*sizeof(PPMPixel*)); //Points to malloc
if((RGBArray == NULL))
{
printf("Error allocating memory to the array");
}
else
{
printf("Memory allocated to the PPM array sucessfully");
}
for (int i=0;i<head.width;i++)
{
RGBArray[i] = (PPMPixel *)malloc(head.width*sizeof(PPMPixel));
}
printf("Error 2");
//Initialising each element
for (int j=0;j<head.height;j++)
{
for (int i=0;i<head.width;i++)
{
fscanf(fp, "%3d %3d %3d ", &p.red, &p.green, &p.blue); //Scans in integers of the address pointer to PPMPixel
data = &RGBArray[i][j]; //Defines data pointer pointing to address of RGBArray[i][j]
data->red = p.red; //Access member of PPMPixel structure to equal one of the three RGB channels
data->green = p.green;
data->blue = p.blue;
}
}
}
fclose(fp);
//Save PPM Array Into New PPM File
FILE *pf;
int i, j;
char fname2[100];
printf("Enter file name: ");
scanf("%s", fname2);
fseek(stdin,0,SEEK_END);
pf = fopen(fname2, "w");
if (pf == NULL)
{
printf("\tError while opening the file\n");
}
else
{
printf("\tWriting in %s\n", fname2);
}
for(j=0;j<head.height;j++)
{
fprintf(pf, "\n");
for(i=0;i<head.width;i++)
{
fprintf(pf, "%3d ", RGBArray[i][j].red);
fprintf(pf, "%3d ", RGBArray[i][j].green);
fprintf(pf, "%3d ", RGBArray[i][j].blue);
//fprintf(pf, "%3d ", (RGBArray+j*head.width + i)*r);
//fprintf(pf, "%3d ", (RGBArray+j*head.width + i)*g);
//fprintf(pf, "%3d ", (RGBArray+j*head.width + i)*b);
}
}
fclose(pf);
free(RGBArray);
RGBArray = NULL;
for(int i=0;i<head.width;i++)
{
free(RGBArray[i]);
RGBArray[i] = NULL;
}
return 0;
}
You mainly mixed width and height, but there are other issues.
width is the number of columns
height is the number of rows
The C two dimensional array in memory order is Row Major.
The convention for storing an image in memory is "by rows".
The indexing is RGBArray[col][row] (in your code it should be RGBArray[j][i]).
Illustration:
RGBArray[0][0] RGBArray[0][14]
| |
V V
<--- width --->
RGBArray[0] -> ############### ^
RGBArray[1] -> ############### |
RGBArray[2] -> ############### height
RGBArray[3] -> ############### |
RGBArray[4] -> ############### V
I used the following PPM text file for testing (in.ppm):
P3
# ppm comment
4 3
255
1 2 3 11 12 13 21 22 23 31 32 33
101 102 103 111 112 113 121 122 123 131 132 133
201 202 203 211 212 213 221 222 223 231 232 233
Corrected code (please read the comments):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxheight 1080
#define maxwidth 1920
#define RGB_COMPONENT_COLOUR 255
#define pgmtype "P2"
#define ppmtype "P3"
typedef struct
{
int red, green, blue;
} PPMPixel;
typedef struct
{
int x, y;
} PPMImage;
typedef struct
{
int rgb_comp_colour;
char filetype[3];
int height;
int width;
} PPMHead;
PPMHead head;
PPMHead* head_ptr = &head;
PPMPixel p;
PPMPixel* p_ptr = &p;
PPMPixel *data; //Defines pointer to PPMPixel
int **Array; //Double pointer defines as a pointer pointing to a pointer that is pointing to an integer
PPMPixel **RGBArray; //Double pointer defines as a pointer pointing to a pointer that is pointing to the PPMPixel structure
FILE *fp;
int r, g, b;
void headercheck()
{
char tmp[201]; //Temporary string.
fscanf(fp, "%2s", head.filetype); //%2s ensures that no more than two characters are read.
fscanf(fp, "%200s", tmp);
if (tmp[0] == '#')
{
//The second line may be a comment starting with '#'
fgets(tmp, 200, fp); //Skip the comment.
fscanf(fp, "%d", &head.width);
}
else
{
//If not a comment, read width from tmp.
sscanf(tmp, "%d", &head.width);
}
//fscanf(fp, "%s %d %d %d", head.filetype, &head.width, &head.height, &head.rgb_comp_colour);
fscanf(fp, "%d %d", &head.height, &head.rgb_comp_colour);
printf("%s %d %d %d", head.filetype, head.width, head.height, head.rgb_comp_colour);
if (head.width > maxwidth || head.height > maxheight)
{
printf("\tInvalid image size. The maximum value of image is 1920x1080.\n");
printf("\tImage size is %d x %d\n", head.width, head.height);
}
else
{
printf("\tImage size is valid\n");
printf("\tImage size is %d x %d\n", head.width, head.height);
}
if ((strcmp(head.filetype, pgmtype) != 0) && (strcmp(head.filetype, ppmtype) != 0))
{
printf("\tInvalid filetype\n");
}
else
{
if (strcmp(head.filetype, pgmtype) == 0)
{
printf("\t File is PGM type image\n");
}
else
{
if (strcmp(head.filetype, ppmtype) == 0)
{
printf("\t File is PPM type image\n");
}
}
}
if ((head.rgb_comp_colour == RGB_COMPONENT_COLOUR))
{
printf("\t Image is 8 bit\n");
}
else
{
if (head.rgb_comp_colour > RGB_COMPONENT_COLOUR)
{
printf("Maximum bit-depth is 8 bits\n");
}
else
{
printf("\tImage is not 8 bit\n");
}
}
}
int main(void)
{
const char *fname = "in.ppm";
//char fname[100];
//printf("Enter file name: ");
//scanf("%s", fname);
//fseek(stdin, 0, SEEK_END);
fp = fopen(fname, "r");
if (fp == NULL)
{
printf("\tError while opening the file\n");
}
else
{
printf("\tReading in %s\n", fname);
}
headercheck();
if (strcmp(head.filetype, ppmtype) == 0)
{
RGBArray = (PPMPixel **)malloc(head.height * sizeof(PPMPixel*)); //Points to malloc
if ((RGBArray == NULL))
{
printf("Error allocating memory to the array\n");
}
else
{
printf("Memory allocated to the PPM array successfully\n");
}
//for (int i = 0; i < head.width; i++)
for (int i = 0; i < head.height; i++) //Iterate height rows
{
RGBArray[i] = (PPMPixel *)malloc(head.width * sizeof(PPMPixel));
if ((RGBArray[i] == NULL))
{
printf("Error allocating memory to the array\n");
}
}
//printf("Error 2");
//Initializing each element
for (int j = 0; j < head.height; j++)
{
for (int i = 0; i < head.width; i++)
{
fscanf(fp, "%3d %3d %3d ", &p.red, &p.green, &p.blue); //Scans in integers of the address pointer to PPMPixel
//data = &RGBArray[i][j]; //Defines data pointer pointing to address of RGBArray[i][j]
data = &RGBArray[j][i]; //The row index comes first - (use [j][i] instead of [i][j])
data->red = p.red; //Access member of PPMPixel structure to equal one of the three RGB channels
data->green = p.green;
data->blue = p.blue;
}
}
}
fclose(fp);
//Save PPM Array Into New PPM File
FILE *pf;
int i, j;
//char fname2[100];
//printf("Enter file name: ");
//scanf("%s", fname2);
//fseek(stdin, 0, SEEK_END);
const char *fname2 = "out.ppm";
pf = fopen(fname2, "w");
if (pf == NULL)
{
printf("\tError while opening the file\n");
}
else
{
printf("\tWriting in %s\n", fname2);
}
//Write the PPM header
////////////////////////////////////////////////////////////////////////////
fprintf(fp, "%s\n", head.filetype);
fprintf(fp, "%d %d\n", head.width, head.height);
fprintf(fp, "%d\n", head.rgb_comp_colour);
////////////////////////////////////////////////////////////////////////////
for (j = 0; j < head.height; j++)
{
//fprintf(pf, "\n");
for (i = 0; i < head.width; i++)
{
//fprintf(pf, "%3d ", RGBArray[i][j].red);
//fprintf(pf, "%3d ", RGBArray[i][j].green);
//fprintf(pf, "%3d ", RGBArray[i][j].blue);
fprintf(pf, "%3d ", RGBArray[j][i].red); //row index comes first - use [j][i] instead of [i][j]
fprintf(pf, "%3d ", RGBArray[j][i].green);
fprintf(pf, "%3d ", RGBArray[j][i].blue);
}
fprintf(pf, "\n");
}
fclose(pf);
//free(RGBArray);
//RGBArray = NULL;
for (int i = 0; i < head.height; i++)
{
free(RGBArray[i]);
RGBArray[i] = NULL;
}
free(RGBArray); //Free RGBArray after free RGBArray[i]
RGBArray = NULL;
return 0;
}
Output file (out.ppm):
P3
4 3
255
1 2 3 11 12 13 21 22 23 31 32 33
101 102 103 111 112 113 121 122 123 131 132 133
201 202 203 211 212 213 221 222 223 231 232 233

Read text file and search the text

After reading the material in the text file, if there is a corresponding name through the search, print out the name and money. However, I can only read the first line of the text file. If I want to make it read another line and find the corresponding name what can I do?
my text file has 15 lines.
Jane 50
Bruno 100
Kim 200
Young 150
Will 250
Jane 50
Bruno 100
Kim 200
Young 150
Will 250
Jane 50
Bruno 100
Kim 335
Young 455
Will 555
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct user{
char name [10];
int money;
} userinformation;
int main()
{
userinformation myvar[100];
int x=0;
char find_name[100];
int i = 0;
int idx = 0;
char buffer[1001],*token;
char* ptr;
userinformation* userinfo;
int cents_50=0;
int cents_20=0;
int cents_10=0;
int cents_5=0;
FILE * srcFile = fopen("coins.txt", "r");
if(srcFile == NULL)
{
printf("fail to open file");
return -1;
}
//file read from coins.txt
while (!feof(srcFile))
{
i =0;
fgets(buffer, 1001, srcFile);
token = strtok(buffer, " ");
while (token != NULL)
{
if(i == 0)
{
strcpy(myvar[idx].name, token);;
}
else if (i == 1)
{
myvar[idx].money = atoi(token);
}
i++;
token = strtok(NULL, " ");
}
idx++;
}
for(int i = 0; i <idx; i++)
{
printf("%s %d\n", myvar[i].name, myvar[i].money);
}
fclose(srcFile);
while(x != 2)
{
printf("1.Enter name\n");
printf("2.Exit\n");
scanf("%d%*c", &x);
if(x ==1)
{
printf("Name: ");
scanf("%s%*c", find_name);
for(i=0; i<idx; i++)
{
ptr = strstr(myvar->name, find_name);
}
if(ptr != NULL)
{
printf("Customer: \n");
printf("%s %d\n", myvar->name, myvar->money);
printf("Change: \n");
//calculate 50cents;
if(myvar->money>50)
{
myvar->money/50;
cents_50++;
printf("50 cents : %d \n", cents_50);
}
//calculate 20cents;
if((myvar->money/50)<50 && myvar->money >=20)
{
if((myvar->money%50/20)>=1)
{
(myvar->money%50/20);
cents_20++;
printf("20 cents : %d \n", cents_20);
}
}
//calculate 10cents;
if((myvar->money%50%20/10)<20 && myvar->money >=10)
{
if((myvar->money%50%20/10)>=1)
{
(myvar->money%50%20/10);
cents_10++;
printf("10 cents : %d \n", cents_10);
}
}
if((myvar->money%50%20%10/5)<10 && myvar->money >=5)
{
if((myvar->money%50%20%10/5)>=1)
{
(myvar->money%50%20%10/5);
cents_5++;
printf("5 cents : %d \n", cents_5);
}
}
}
else if(ptr != myvar->name)
{
printf("Not founded\n");
}
}
else if(x ==2)
break;
}
return(0);
}
'''
This seems wrong:
for(i=0; i<idx; i++)
{
ptr = strstr(myvar->name, find_name);
}
myvar is an array but you don't use an array index. In other words - you always use the first element of the array (i.e. myvar[0].name).
Besides that, I would expect that the loop should stop when strstr return a non-NULL value.
Did you intend to do:
for(i=0; i<idx; i++)
{
ptr = strstr(myvar[i].name, find_name);
if (ptr != NULL) break;
}
(btw - do you really want to use strstr? I would expect a string compare using strcmp ).
The same problem, i.e. missing array index, is present in all the code that follows the above code.
BTW: The way you read from the file isn't 100% correct. See Why is “while ( !feof (file) )” always wrong?

I am encountering a segmentation fault in my c code

I am trying to update a 2d array generation by generation.
In order to do this, I need to take two arguments: generation number and the initial input txt that contains a 2d array.
But no matter what I wrote, there are always segmentation fault in my code.
I am trying to read a 2d array from the input file.
The file should look similar to this:
1 1 1 0 0
0 0 0 0 0......
int main(int argc, char *argv[]) {
// take arguments//
char* generation;
char* filename;
if (argc < 2)
{
printf("Error\n");
exit(1);
}
else{
generation = argv[1];
filename = argv[2];
}
// read file as a 5*5 matrix//
FILE *file;
file = fopen (filename,"r");
//5*5 matrix//
int gen = atoi(generation);
int cell[5][5];
int i=0;
int j=0;
for (i=0;i<5;i++){
for (j=0;j<5;j++){
fscanf (file, "%d",&cell[i][j]);
}
}
fclose(file);
Thank you so much!!!
In your code you're not using the variable generation but I suppose it should be used to store the matrix dimension. If it is the case in total you're reading 3 arguments so argc should be 3.
If you are reading a file formatted like this:
1 2 3 4 5
6 7 8 9 10
1 1 3 4 5
6 7 8 9 0
The arguments passed at the console are: ./a.out dimension matrix. A simple but unsafe code (it doesn't check the dimension input by the user) is the following:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *fp;
char *filename;
char *generation;
if (argc < 3)
{
printf("Error\n");
exit(1);
}
else {
generation = argv[1];
filename = argv[2];
fp = fopen(filename, "r");
if (fp == NULL) {
fprintf(stderr, "Error: Cannot open file %s for reading\n", filename);
exit(1);
}
}
int dim = atoi(generation);
int i, j, cell[dim][dim];
for (i = 0; i < dim; i++) {
for (j = 0; j < dim; j++) {
if (fscanf(fp, "%d ", &cell[i][j]) != 1) {
fprintf(stderr, "invalid input for cell[%d][%d]\n", i, j);
fclose(fp);
exit(1);
}
}
}
fclose(fp);
/*Print the matrix */
for (i = 0; i < dim ; i++)
{
for (j = 0; j < dim ; j++)
{
printf("%d ", cell[i][j]);
}
printf("\n");
}
printf("\n");
return 0;
}

runtime error when trying to read data from file

I have a question on logical error, the error was
"Run-Time Check Failure #2 - Stack around the variable 'list' was corrupted."
there are a total of 60 lines in the in.txt file
this is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILE_NAME 20
#define LIST_SIZE 50
//void getData(RECORD name[], RECORD score)
typedef struct
{
char *name;
int score;
}RECORD;
int main (void)
{
// Declarations
FILE *fp;
char fileName[FILE_NAME];
RECORD list[LIST_SIZE];
char buffer[100];
int count = 0;
int i;
// Statements
printf("Enter the file name: ");
gets(fileName);
fp = fopen(fileName, "r");
if(fp == NULL)
printf("Error cannot open the file!\n");
while(fgets(buffer, 100, fp) != NULL)
{
list[count].name = (char*) calloc(strlen(buffer), sizeof(RECORD*));
if(count > 50)
{
}
if( count < 50)
{
sscanf(buffer,"%[^,], %d", list[count].name, &list[count].score);
for( i =1; i < (50 - count); i++)
{
list[count + i].name = 0;
list[count + i].score = 0;
}
}
count++;
}
printf("Read in %d data records\n", count);
fclose(fp);
return 0;
}
in this program I' m trying to read data from file to array of structures, so if the number of data is less than 50, structures that don't have data will be zero out and if the number of data is more than 50 the program will only read the first 50 structures.
how can i fix the runtime error?
Perhaps...
while(fgets(buffer, 100, fp) != NULL)
{
if( count >= 50)
{
break;
}
if( count < 50)
{
list[count].name = (char*) malloc(strlen(buffer)*sizeof(char));
sscanf(buffer,"%[^,], %d", list[count].name, &list[count].score);
count++;
}
}
for( i =0; i < (50 - count); i++)
{
list[count + i].name = 0;
list[count + i].score = 0;
}
What if count = 50?
Try with the following in your while loop bringing if block in the start or at the end;
if(count >= 50) //count should be checked for >= 50 before being used.
{
}
list[count].name = (char*) calloc(strlen(buffer), sizeof(RECORD*)); //list size is 50 so list[50] won't work. out of bound.

Resources