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

时间:2015-12-06 21:07:04

标签: c malloc realloc

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

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])

我必须输入一个单词数组,我不知道它们的长度。在这段代码中,我只能输入某个长度的单词,我想改变它。

2 个答案:

答案 0 :(得分:1)

@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每个字符串,则可以稍后再执行。如果您需要更改分配的字符串数量(执行reallocstrings),则可能会稍微复杂一点。

答案 1 :(得分:-2)

分配字符串数组char ** mystrs = malloc(numstrings * sizeof(char *))。现在,mystrs是一个指针数组。现在您需要做的就是为要添加的每个字符串使用malloc。

mystrs [0] = malloc(numchars +1 * sizeof(char))。 //为空字符添加额外的字符

然后你可以用strcpy复制字符串数据。 strcpy(mystrs [0],“my string”)

相关问题