C语言 如何在 C 中动态分配字符串数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7652293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:48:40  来源:igfitidea点击:

How do I dynamically allocate an array of strings in C?

c

提问by John Bode

If I have the number of items in a var called "totalstrings" and a var called "string size" that is the string size of each item, how do I dynamically allocate an array called "array?"

如果我有一个名为“totalstrings”的变量和一个名为“string size”的变量,它是每个项目的字符串大小,我如何动态分配一个名为“array”的数组?

This is an array of strings in C, not C++.

这是 C 中的字符串数组,而不是 C++。

Thanks!

谢谢!

回答by mah

NOTE: My examples are not checking for NULL returns from malloc()... you really should do that though; you will crash if you try to use a NULL pointer.

注意:我的示例没有检查 malloc() 的 NULL 返回……不过您确实应该这样做;如果您尝试使用 NULL 指针,您将崩溃。

First you have to create an array of char pointers, one for each string (char *):

首先,您必须创建一个字符指针数组,每个字符串 (char *) 一个:

char **array = malloc(totalstrings * sizeof(char *));

char **array = malloc(totalstrings * sizeof(char *));

Next you need to allocate space for each string:

接下来你需要为每个字符串分配空间:

int i;
for (i = 0; i < totalstrings; ++i) {
    array[i] = (char *)malloc(stringsize+1);
}

When you're done using the array, you must remember to free()each of the pointers you've allocated. That is, loop through the array calling free()on each of its elements, and finally free(array)as well.

使用完数组后,您必须记住free()已分配的每个指针。也就是说,遍历数组调用free()它的每个元素,最后free(array)也是。

回答by John Bode

The common idiom for allocating an N by M array of any type T is

分配任何类型 T 的 N × M 数组的常用习惯用法是

T **a = malloc(N * sizeof *a);
if (a)
  for (i = 0; i < N; i++)
    a[i] = malloc(M * sizeof *a[i]);

As of the 1989 standard, you don't need to cast the result of malloc, and in fact doing so is considered bad practice (it can suppress a useful diagnostic if you forget to include stdlib.h or otherwise don't have a prototype for mallocin scope). Earlier versions of C had mallocreturn char *, so the cast was necessary, but the odds of you having to work with a pre-1989 compiler are pretty remote at this point. C++ doesrequire the cast, but if you're writing C++ you should be using the newoperator.

从 1989 年标准开始,您不需要转换 的结果malloc,实际上这样做被认为是不好的做法(如果您忘记包含 stdlib.h 或没有原型,它会抑制有用的诊断)malloc在适用范围)。早期版本的 C 有mallocreturn char *,因此强制转换是必要的,但是此时您必须使用 1989 之前的编译器的可能性非常小。C++确实需要强制转换,但如果您正在编写 C++,则应该使用new运算符。

Secondly, note that I'm applying the sizeofoperator to the object being allocated; the type of the expression *ais T *, and the type of *a[i]is T(where in your case, T== char). This way you don't have to worry about keeping the sizeofexpression in sync with the type of the object being allocated. IOW, if you decide to use wcharinstead of char, you only need to make that change in one place.

其次,请注意,我将sizeof运算符应用于正在分配的对象;表达式的类型*aT *,类型*a[i]T(在你的情况下,T== char)。这样您就不必担心保持sizeof表达式与正在分配的对象的类型同步。IOW,如果您决定使用wchar而不是char,则只需在一个地方进行更改。

回答by Chriszuma

char** stringList = (char**)malloc(totalStrings * sizeof(char*));

for( i=0; i<totalStrings; i++ ) {
  stringList[i] = (char*)malloc(stringSize[i]+1);
}

回答by Pete Wilson

Well, first you might want to allocate space for "array", which would be an array of char * that is "totalstrings" long.

好吧,首先您可能想要为“array”分配空间,这将是一个长度为“totalstrings”的 char * 数组。

What would then be the starting and final indexes in "array"? You know the first one is 0; what's the last one?

那么“数组”中的起始索引和最终索引是什么?你知道第一个是 0;最后一个是什么?

Then, for each entry in "array", you could (if you wanted) allocate one area of memory that is "stringsize+1" (why +1, pray tell me?) long, putting the starting address of that area -- that string -- into the correct member of "array."

然后,对于“数组”中的每个条目,您可以(如果需要)分配一个“stringsize+1”(为什么是 +1,请告诉我?)长的内存区域,并放置该区域的起始地址——该字符串 - 放入“数组”的正确成员中。

That would be a good start, imo.

这将是一个好的开始,imo。