简体   繁体   English

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

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

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!谢谢!

NOTE: My examples are not checking for NULL returns from malloc()... you really should do that though;注意:我的示例没有检查 malloc() 的 NULL 返回……不过你确实应该这样做; you will crash if you try to use a NULL pointer.如果您尝试使用 NULL 指针,您将崩溃。

First you have to create an array of char pointers, one for each string (char *):首先,您必须创建一个字符指针数组,每个字符串 (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.当你使用完数组后,你必须记住free()你分配的每个指针。 That is, loop through the array calling free() on each of its elements, and finally free(array) as well.也就是说,循环遍历数组,在其每个元素上调用free() ,最后也调用free(array)

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 malloc in scope).从 1989 年标准开始,您不需要转换malloc的结果,实际上这样做被认为是不好的做法(如果您忘记包含 stdlib.h 或没有原型,它会抑制有用的诊断)用于范围内的malloc )。 Earlier versions of C had malloc return 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 有malloc返回char * ,因此强制转换是必要的,但是此时您必须使用 1989 之前的编译器的可能性非常小。 C++ does require the cast, but if you're writing C++ you should be using the new operator. C++确实需要强制转换,但是如果您正在编写 C++,则应该使用new运算符。

Secondly, note that I'm applying the sizeof operator to the object being allocated;其次,请注意我将sizeof运算符应用于正在分配的对象; the type of the expression *a is T * , and the type of *a[i] is T (where in your case, T == char ).表达式*a的类型是T * ,而*a[i]的类型是T (在您的情况下, T == char )。 This way you don't have to worry about keeping the sizeof expression in sync with the type of the object being allocated.这样您就不必担心保持sizeof表达式与正在分配的对象的类型同步。 IOW, if you decide to use wchar instead of char , you only need to make that change in one place. IOW,如果您决定使用wchar而不是char ,则只需在一个地方进行更改。

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

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

I know this question is old and was already answered.我知道这个问题很老,已经回答了。 I just want to point out that malloc is a system call and shouldn't be used multiple times.我只想指出malloc是一个系统调用,不应多次使用。

It would be better to allocate one big chunk of memory and make the array point to it.最好分配一大块内存并使数组指向它。 Something like this :像这样的事情:

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

#define STR_SIZE 100 //STR_SIZE doesn't have to be a constant

int main(){
        int i;
        char **arr;
        char *long_string;
        long_string = (char *)malloc(sizeof(char)*STR_SIZE*10);
        arr = malloc(sizeof(char *)*10);

        //Pointing each item of the array to an allocated memory. 
        for (i=0; i<10; i++){
                arr[i] = (long_string + STR_SIZE * i);
        }

        //Initialising the array
        for (i=0; i<10; i++){
                strcpy(arr[i], "This is a line in a\
 paragraph\n");
        }

        //Printing the items of the array
        for (i=0; i<10; i++){
                printf("%s \n", arr[i]);
        }

        //freeing the allocated memory
        free(long_string);
        free(arr);

        return 0;
}

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;你知道第一个是 0; what's the last one?最后一个是什么?

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。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM