gpt4 book ai didi

c - 将值存储到结构数组值 C

转载 作者:行者123 更新时间:2023-11-30 17:33:57 25 4
gpt4 key购买 nike

我正在尝试读取文件并将值存储到结构数组中,然后将值传递给函数。第一个 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;
}

最佳答案

也许是这样的:

#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);
}

关于c - 将值存储到结构数组值 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23577633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com