我正在尝试读取文件并将值存储到struct数组中,然后将值传递给函数。第一个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;
}
答案 0 :(得分:0)
也许是这样的:
#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);
}