【问题标题】:How to use a 2D array of pointers in C to store strings?如何在 C 中使用二维指针数组来存储字符串?
【发布时间】:2015-09-20 06:24:09
【问题描述】:

假设我有一个文件,其中包含以下字符串:

option0 value0
option1 value1
....... ......
optionX valueX 

我正在尝试制作一个 C 程序来读取文件。 我决定创建一个指向字符串的二维指针数组,并将所有选项存储在第一行的指针对象中,并将所有值存储在第二行的指针对象中。这样:

pointer[0][0] should point to option0
pointer[1][0] should point to value0
pointer[0][1] should point to option1
pointer[1][1] should point to value1

程序似乎成功读取了文件,但我无法访问字符串以将它们打印出来。 这是导致问题的代码的精简版本:

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

int main (void) {

#define BUFF 1024

FILE *fd;
int i = 0;
char buff[BUFF];
char *options [2][20];

fd = fopen("foo.txt", "r");

while (!feof(fd)) {

if (fgets(buff, sizeof(buff), fd) != NULL) {

        (options[0][i] = malloc(sizeof (char) * 512)
        (options[1][i] = malloc(sizeof (char) * 512)

                sscanf(buff, "%s %s", options[0][i], options[1][i]);
                i++;

}
}

while (i >= 0) {

printf ("Option %i is %s its value is %s", i, *option[0][i], *option[1][i]);

i--;
}
fclose(fd);
return 0;
}

我玩了几天,但我似乎无法让它工作。我检查了各种 Stackoverflow 问题和其他在线资源,但即使是实验也无法帮助我弄清楚这一点。

我想知道的是: 字符串是否使用 malloc 和 sscanf 正确存储?如果“不”,为什么? 为什么我无法使用 printf 语句打印字符串?如何解决?

请注意,显示的代码仅用于测试目的,所以我知道没有错误检查等。

【问题讨论】:

  • 不要使用feof 来控制循环。 while(!feof(fd)) 总是错的
  • 不要在 C 中使用二维数组。在需要时使用arr[i*width+j]。顺便说一句,你想要一个hash table
  • @ameyCU 感谢您的建议,我会确保进行调整。
  • @BasileStarynkevitch C 中的二维数组有什么问题?
  • 它们唯一的用例是在实践中用于固定维度的二维数组(此处不适合:文件可能超过 20 行)。

标签: c arrays pointers multidimensional-array


【解决方案1】:

在将指针提供给printf 时,您正在取消引用它们。它需要char*,而不是char%s

printf ("Option %i is %s its value is %s", i, *option[0][i], *option[1][i]);

这应该是

printf ("Option %i is %s its value is %s", i, option[0][i], option[1][i]);

另一个问题是您必须在 while 循环中打印之前减少 i。你在每次内存分配后递增它,所以最后它指向最后一个元素。将i--; 移动到while 循环中的第一个位置。

此外,sizeof(char) 始终为 1,因此在计算 malloc() 的大小时不需要它。

请同时将编译器的警告调整到更高的级别。例如带有-Wall 的 gcc 会说:

警告:格式“%s”需要“char *”类型的参数,但参数 2 的类型为“int”[-Wformat=]

【讨论】:

  • 我按照建议调整了 printf 语句,但仍然出现“Segmentation fault”错误。
  • @zilog 添加了另一个可能导致此崩溃的问题。
  • 谢谢!我还发现while (i &gt;= 0) 应该是while (i &gt; 0)。我现在也没有收到任何警告。
  • 我应该在 printf 之前递减我错了吗? @zilog
【解决方案2】:

1) i-- 必须在 printf 之前

2) 正如 Sami 的回答,不要取消引用 printf 中的指针

while (0 <=-- i)
    printf ("Option %i is %s its value is %s", i, option[0][i], option[1][i]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多