char *在一个结构中传递给函数。如何访问这些数据?

问题描述 投票:0回答:1
typedef struct school_ {
    char *name;
    char *state;
} School;

以上是我需要用于以格式存储文件数据的结构格式

姓名,州

name2,state2

下面给出了一个指针数组的声明,第二行是如何调用该函数。

School *TOP100[school_size];

input_schools(school_info,TOP100,school_size);

在我的函数中,我需要存储一个动态字符串作为100所学校的名称。

我写了以下内容,但是遇到了一个段错误。如何在不更改上述代码的情况下更改我的功能?

void input_schools(FILE *IN, School **Sch, int k) {
    printf("in input_schools() ... \n\n\n");

    int i, j = 0;
    char ch;

    for (i = 0; i < k; i++) {
        fscanf(IN, "%c", &ch);
        Sch[i]->name = (char *) malloc(sizeof (char));
        j = 0;
        Sch[i]->name[j] = ch;

        while (ch != ',') {
            fscanf(IN, "%c", &ch);
            j++;
            Sch[i]->name = (char *) realloc(Sch[i]->name, sizeof(char) * (j + 1));
            Sch[i]->name[j] = ch;
        }
        Sch[i]->name[j - 1] = '\0';
    }

    return;
}

这段代码编译时会返回一个seg错误。

c pointers struct
1个回答
0
投票

我认为更简单的方法是使用C库来获得优势。我没有你的输入文件,但这应该工作或至少让你更接近:

void input_schools(FILE *IN, School **Sch, int school_size)
{
  printf("in input_schools() ... \n\n\n");

  char *name;
  char *state;
  char *line;
  size_t line_len;

  for(int i=0; i<school_size; ++i) {
    line = NULL;
    line_len=0;

    // get line: line will contain a newly-allocated string
    // that holds a single line from the file
    if(-1 == getline(&line, &line_len, IN)) {
      // end of file reached
      break;
    }

    // make a new school
    Sch[i] = (School*)malloc(sizeof(School));

    // allocate storage for the name and state
    name = malloc(line_len); // we know that line_len is >= the size of the name
    state = malloc(line_len); // we know that line_len is >= the size of the state

    // everything before the = is the name, everything after is the state
    sscanf(line, "%[^=]s = %[^=]s", name, state);

    // free the memory getline() allocated
    free(line);

    Sch[i]->name = name;
    Sch[i]->state = state;
  } // end for all possible schools
} // end input_schools
© www.soinside.com 2019 - 2024. All rights reserved.