简体   繁体   中英

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:

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.

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 .

A structure always has the same size so with this implementation you'd be stuck with always having an array of size 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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