简体   繁体   English

带字符串数组的C程序malloc

[英]C program malloc with array of strings

At the beginning of a program I need to dynamically allocate memory for an unknown number of strings with unknown number of size to later manipulate with. 在程序开始时,我需要为未知数量的字符串(大小未知)动态分配内存,以便以后使用。 To get the number of strings from a user I have: 要获得用户的字符串数,我需要:

int main(int argc, char *argv[]){

int number = atoi(argv[1]);

So far so good. 到现在为止还挺好。 "number" now holds holds the number that the user inputted on the command line for executing the code. 现在,“ number”保存着用户在命令行上输入的用于执行代码的数字。 Now here comes the part I don't quite understand. 现在是我不太了解的部分。 I now need to dynamically store the lengths of the strings as well as the contents of the strings. 现在,我需要动态存储字符串的长度以及字符串的内容。 For example, I want the program to function like this: 例如,我希望程序运行如下:

Enter the length of string 1: 5
Please enter string 1: hello
Enter the length of string 2: ...

For this I recognize that I will have to create an array of strings. 为此,我认识到必须创建一个字符串数组。 However, I can't quite understand the concept of pointers to pointers and what not. 但是,我不太了解指针的概念,而没有。 What I would like is perhaps a simplification of how this gets accomplished? 我想要的可能是如何简化此过程?

You know from the start you will have number strings to store so you will need an array of size number to store a pointer to each string. 您从一开始就知道要存储number字符串,因此需要一个大小为number的数组来存储指向每个字符串的指针。

You can use malloc to dynamically allocate enough memory for number char pointers: 您可以使用mallocnumber char指针动态分配足够的内存:

char** strings = malloc(number * sizeof(char*));

Now you can loop number times and allocate each string dynamically: 现在,您可以循环number次数和动态分配每个字符串:

for (int i = 0; i < number; i++) {
   // Get length of string
   printf("Enter the length of string %d: ", i);
   int length = 0;
   scanf("%d", &length);

   // Clear stdin for next input
   int c = getchar(); while (c != '\n' && c != EOF) c = getchar();

   // Allocate "length" characters and read in string
   printf("Please enter string %d: ", i);
   strings[i] = malloc(length * sizeof(char));
   fgets(strings[i], length, stdin);
}

Since you want to save both the length and the string, I'll suggest that you put them together in a struct. 既然你要保存的长度和字符串,我会建议你把它们放在一起的结构。 Like 喜欢

struct string
{
    int length;
    char* str;
};

Now you can dynamically create an array of this struct and dynamically assign memory for the individual strings. 现在,您可以动态创建此结构的数组,并为各个字符串动态分配内存。

Something like: 就像是:

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

struct string
{
    int length;
    char* str;
};

int main(void) {
    int i;
    char tmp[128];
    int number = 3;
    struct string* strings = malloc(number * sizeof *strings);

    // read the input
    for (i=0; i<number; ++i)
    {
        printf("length?\n");
        if (fgets(tmp, sizeof tmp, stdin) == NULL)
        {
            printf("error 1");
            exit(1);
        }
        int length;
        if (sscanf(tmp, "%d", &length) != 1)
        {
            printf("error 2");
            exit(1);
        }
        strings[i].length = length;
        strings[i].str = calloc(length + 2, 1);
        printf("string?\n");
        if (fgets(strings[i].str, length + 2, stdin) == NULL)
        {
            printf("error 3");
            exit(1);
        }
        if (strings[i].str[length] != '\n')
        {
            printf("error 4");
            exit(1);
        }
        strings[i].str[length] = '\0';
    }

    // print the strings
    for (i=0; i<number; ++i)
    {
      printf("len=%d str=%s\n", strings[i].length, strings[i].str);
    }

    // Clean up, i.e. free the memory allocated
    for (i=0; i<number; ++i)
    {
        free(strings[i].str);
    }
    free(strings);

    return 0;
}

Note : You should also check that all malloc / calloc are succesful, ie doesn't return NULL. 注意 :您还应该检查所有malloc / calloc是否成功,即不返回NULL。 For clarity I skipped that. 为了清楚起见,我略过了。

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

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