char *在传递给函数的结构中。如何访问此数据?

时间:2018-11-13 22:00:45

标签: c pointers struct

typedef struct school_ {
    char *name;
    char *state;
} School;

以上是我用来存储文件格式的结构所需要的结构格式

名称,州

名称2,状态2

在下面,我得到了一个指针数组的声明,第二行是函数的调用方式。

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

此代码编译时将返回段错误。

1 个答案:

答案 0 :(得分: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