1

这个想法是从标准输入读取字符串,直到达到 EOF(以这种格式"string - string")。然后,将字符串分成两个字符串并将它们保存到二维数组中。该数组是动态分配的,最初有 2 行和 20 列,但我想每次添加下一个字符串时添加 2 行(函数expandmat())。这是我的代码:

char ** alloc(int rows, int collums) {
   char ** mat;
   int i;
   mat = malloc(sizeof (char *) * rows);
   for (i = 0; i < rows; i++) {
      mat[i] = malloc(sizeof (char) * collums);
   }
   return mat;
}

char ** addtoarray(char ** mat, char * string1, char * string2, int position) {

   sscanf(string1, "%s", mat[positon]);
   sscanf(string2, "%s", mat[positon+1]);
   return mat;
}

char ** getinput(char * longstring, char * string1, char * string2) {

   int position = 0, n = 2, max = 30;
   char ** mat;
   mat = alloc(n, max);
   while (fgets(longstring, max, stdin)) {
        sscanf(longstring, "%s - %s", string1, string2);
        addtoarray(mat, string1, string2, positon);
        n += 2;
        position += 2;
        mat = expandmat(mat, n);
   }

   return mat;
}

另外,如果这段代码中有一些没有任何意义的东西,你能告诉我如何解决它吗?

我知道这似乎是一项微不足道的任务,但它一直让我发疯。

谢谢你的帮助。

4

2 回答 2

0

Wow... The third time that a question like this comes up for today :-).

Please check if my answer here helps you: Array of C structs

于 2011-02-05T22:46:39.347 回答
0

查看reallocC 函数来调整垫子的大小。

expandmat应该 realloc mat 以便您可以再添加两行(它也应该返回矩阵,因为 realloc 会在必要时将内存复制到新位置)

于 2011-02-05T22:43:05.507 回答