gpt4 book ai didi

使用 C 中固定的行数创建二维数组

转载 作者:太空宇宙 更新时间:2023-11-04 07:35:12 24 4
gpt4 key购买 nike

我想创建一个维度为“string[5][*]”的二维字符串数组,但遇到了一些问题。我想做这样的事情:

...
for(i = 0;i < 5;i++){
char* word = ...;
if(strcmp(word,...)){
string[i][j] = (char *) malloc(/*size of word*/);
string[i][j] = word;
j++;
}
}

“字符串”变量在第 i 个方向上的长度应为 5,并且应允许在第 j 个方向上增长到我需要的长度。

我试过:

char* string[5];

但这似乎不起作用。请注意上面的 for 循环已经过简化,部分内容可能看起来不合逻辑。

编辑:我正在尝试将字符串列表分为 5 个类别。因此,n 维数组在某种意义上应该包含 5 个包含未指定数量的字符串(不是字符)的数组。我假设这是一个 3 维字符数组,但在思考如何编写它时遇到了麻烦。我希望每个 string[i][j] 项都包含一个 char 数组。所以 string[0][0] 可能等于“猫”或其他东西。

最佳答案

试试这个。

char **string;
string = (char **)(malloc(sizeof(char *) * 5));
//malloc the string[i] whenever you need to at what ever size is necessary.

同样在您顶部的代码中,问题是每个 string[i][j] 都是一个 char 并且您不能为非指针分配 malloc。每个 string[i] 都是一个 char * 你必须为此 malloc。

关于使用 C 中固定的行数创建二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9659455/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com