简体   繁体   English

动态分配字符串数组

[英]Dynamically allocating array of strings

I want to dynamically allocate array of strings, but I'm not sure how I can do this. 我想动态分配字符串数组,但是我不确定如何做到这一点。 So I thought of making a struct and dynamically allocate that struct. 因此,我想到了一个结构并动态分配该结构。 So I made the code below, but this code creates assertion failure. 因此,我在下面编写了代码,但是此代码创建了断言失败。

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

typedef struct {
    char str1[20];
    char str2[20];
} String;

int main(void)
{
    String * list;
    list = (String *)malloc(sizeof(String));
    int i = 1;

    for (; i < 6; i++) {
        realloc(list, i * sizeof(String));
        printf("Input String 1: ");
        scanf("%s", list[i - 1].str1);
        printf("Input String 2: ");
        scanf("%s", list[i - 1].str2);
    }

    for (i = 0; i < 5; i++)
        printf("%s\t%s\n", list[i].str1, list[i].str2);
    free(list);
}

What have I done wrong and how can I fix this problem? 我做错了什么,该如何解决呢?

Thanks :) 谢谢 :)

The man page for realloc says: 重新realloc的手册页显示:

The realloc() function returns a pointer to the newly allocated memory, which is suitably aligned for any kind of variable and may be different from ptr, or NULL if the request fails. realloc()函数返回一个指向新分配的内存的指针,该指针适合于任何类型的变量,并且可能与ptr不同,如果请求失败,则为NULL。

The new pointer can be different from the one you passed to realloc , so you need to collect and use the pointer returned by realloc . 新指针可以与传递给realloc指针不同,因此您需要收集并使用realloc返回的指针。

A structure always has the same size so with this implementation you'd be stuck with always having an array of size 2. 结构始终具有相同的大小,因此使用此实现时,您将始终拥有大小为2的数组。

A way to declare an array of strings (which are themselves arrays of characters) s doing 声明字符串数组(本身就是字符数组)的一种方法

char **string;

If you want an array of 20 strings then that'd be: 如果您想要20个字符串组成的数组,则为:

string = malloc(sizeof(char*)*20); 

Structs must have constant size, so i don't think the compiler will like you trying to allocate more memory for a structure than what it was defined with. 结构必须具有恒定的大小,因此我不认为编译器会喜欢您尝试为结构分配比其定义的更多的内存。

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

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