gpt4 book ai didi

c - 如何在 C 中创建动态字符串数组?

转载 作者:行者123 更新时间:2023-11-30 21:31:39 25 4
gpt4 key购买 nike

我想创建一个字符串数组,其中每个字符串都没有固定长度。我该怎么做?这是我的代码:

char **a;
int n, m;
scanf_s("%d %d", &n, &m);
a = (char**)malloc(n*sizeof(char*));
for (int i = 0; i < n; i++)
a[i] = (char*)malloc(m*sizeof(char));

for (int i = 0; i < n; i++)
for (int j = 0; j < m;j++)
scanf_s(" %c", &a[i][j])

我必须输入一组单词,但我不知道它们的长度。在此代码中,我只能输入一定长度的单词,我想更改它。

最佳答案

@Daniel 所说的一个例子是:

int NumStrings = 100;
char **strings = (char**) malloc(sizeof(char*) * NumStrings);
for(int i = 0; i < NumStrings; i++)
{
/*
Just an example of how every string may have different memory allocated.
Note that sizeof(char) is normally 1 byte, but it's better to let it there */
strings[i] = (char*) malloc(sizeof(char) * i * 10);
}

如果您不需要在开头对每个字符串进行malloc,则可以稍后再进行。如果您需要更改分配的字符串数量(对strings执行realloc),那么它可能会稍微复杂一些。

关于c - 如何在 C 中创建动态字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34122760/

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