[英]store values to struct array values C
I'm trying to read a file and store the values into struct array then pass the values to a function. 我正在尝试读取文件并将值存储到struct数组中,然后将值传递给函数。 the first printf shows the right values but the second one gives all 0. when passing the values to the function it passes all 0 too.
第一个printf显示正确的值,但是第二个printf显示全0。将值传递给函数时,它也传递全0。
input data
0 1
0 2
0 3
0 4
0 5
typedef struct
{
int brust_time[MAX];
int arrival_time[MAX];
}Time;
int main()
{
Time *foo;
FILE *fr;
char str[10];
int x = 0;
int m;
fr = fopen("read.txt", "rt");
while(fgets(str, 10, fr) != NULL)
{
x++;
foo = (Time *) malloc(sizeof(Time));
sscanf(str, "%d %d", foo[x].arrival_time,foo[x].brust_time );
printf("x: %d B:%d\n", *foo[x].arrival_time, *foo[x].brust_time);
}
for( m = 0; m <x; m++)
printf("*****x: %d ******B:%d\n", *foo[m].arrival_time, *foo[m].brust_time);
SJF(foo[x].brust_time,foo[x].arrival_time, x);
fclose(fr);
return 0;
}
Perhaps something like this: 也许是这样的:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#define MAX 10
typedef struct
{
int brust_time;
int arrival_time;
}Time;
int main()
{
int rCode=0;
Time *foo = NULL;
FILE *fr = NULL;
char str[10];
int x = 0;
int m;
/* Open the data file in read (text) mode) */
errno=0;
fr = fopen("read.txt", "rt");
if(NULL == fr)
{
rCode=errno;
fprintf(stderr, "fopen() failed. errno[%d]\n", errno);
goto CLEANUP;
}
/* Allocate an array of 'Time' structures large enough to hold all the data. */
foo = malloc(MAX * sizeof(Time));
if(NULL == foo)
{
rCode=ENOMEM;
fprintf(stderr, "malloc() failed.\n");
goto CLEANUP;
}
/* Read, parse, and store each line's data in the array of structures. */
while(x<MAX)
{
/* Read a line. */
errno=0;
if(NULL == fgets(str, 10, fr))
{
if(feof(fr))
break;
rCode=errno;
fprintf(stderr, "fgets() failed. errno[%d]\n", errno);
goto CLEANUP;
}
/* Parse & store */
sscanf(str, "%d %d", &foo[x].arrival_time, &foo[x].brust_time );
++x;
}
/* Generate report. */
for(m = 0; m < x; m++)
printf("*****x: %d ******B:%d\n", foo[m].arrival_time, foo[m].brust_time);
/* Restore system. */
CLEANUP:
/* Free Time structure array. */
if(foo)
free(foo);
/* Close the file. */
if(fr)
fclose(fr);
return(rCode);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.