gpt4 book ai didi

c - 在函数中传递结构体

转载 作者:行者123 更新时间:2023-11-30 17:43:09 24 4
gpt4 key购买 nike

我花了很多时间在函数中传递结构指针。代码中的所有内容都正常工作,只是我无法弄清楚如何在函数中传递结构,然后我可以在函数内执行一些操作。你能解释一下我到底失败在哪里以及如何解决它吗?谢谢。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int i=0;
int* i_ptr=&i;
int count(int q);
int line_count();

struct student {
int st_id;
char st_name[20];
int st_age;
char st_dep[7];
float st_grade;
};

int sort_student(struct student line[i],int i)
{
printf("%f",line[1].st_grade);
printf(" %s",line[1].st_name);

return 0;
}

int main()
{
/* struct loading from the file operation goes here */
int x=0;
int i=line_count();
struct student line[i];
char file_line[100];
char* line_parts;

FILE * fp;
if ((fp = fopen (file.txt", "r")) != NULL)
{
while (x<i) {
if(fgets(file_line,100,fp) != NULL); // gets line from the file.
{
line_parts = strtok(file_line,","); // breaks the line
line[x].st_id = atoi(line_parts); // conversition string to int

line_parts = strtok(NULL, ",");
strcpy(line[x].st_name,line_parts);

line_parts = strtok(NULL, ",");
line[x].st_age = atoi(line_parts);

line_parts = strtok(NULL, ",");
strcpy(line[x].st_dep,line_parts);

line_parts = strtok(NULL, ",");
line[x].st_grade = atoi(line_parts);
x++;
}
}
}
fclose(fp);

sort_student(&line[i],i);
return 0;
}

int line_count () //counts the number of line in the file, while loading the program.
{
FILE * fp; // file open from here.
int i=0;
int c;
if ((fp = fopen ("/Users/rishav/Desktop/try/try/file.txt", "r")) != NULL)
{
while ((c=fgetc(fp)) != EOF) {
if (c=='\n') {
i++;
}
}
fclose(fp);
}
else printf("file reading Error.\n");
return i;
}

int count(q) // keeps track of i
{
if(q==1)
{
(*i_ptr)++;
}
return *i_ptr;
}

最佳答案

您需要将 sort_student 函数定义更改为

int sort_student(struct student* line,int i) {
printf("%f",line->st_grade);
printf(" %s",line->st_name);

return 0;
}

关于c - 在函数中传递结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20294025/

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