在函数中传递struct

时间:2013-11-29 22:13:07

标签: c pointers struct

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

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

1 个答案:

答案 0 :(得分:0)

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

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

    return 0;  
}