如何为C中的字符串数组动态分配内存? [处于保留状态]

问题描述 投票:-1回答:2

我想要一个字符串数组。我想通过动态内存分配来创建它,以便每个输入的单词都有每个数组x [n]。我只想使用必要的内存,但不要更多。

c arrays string dynamic allocation
2个回答
0
投票

这里是在堆栈上分配指针数组并在堆上分配字符串本身的版本。

您可能想要修改此示例,以便指针数组也得到动态分配。与该示例相关的是,我将使用realloc来使指针数组增长。

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

int main()
{
    const int MAX_WORDS = 12;
    char tmp[25];
    char *pWords[MAX_WORDS];
    int length;
    int n = 0;
    int i;
    printf("Please enter words:\n");
    do {
        printf("%d: ", n);
        fgets(tmp, sizeof(tmp), stdin); // contains also new-line char
        length = strlen(tmp);
        pWords[n] = malloc(length+1);
        if (pWords[n])
        {
            strcpy(pWords[n], tmp);
            n++;
        }
        else
        {
            break;
        }
    } while (tmp[0]!='\n' && n<MAX_WORDS);

    for (i=0; i<n; i++)
    {
        printf("Words[%d] = %s", i, pWords[i]);
        free(pWords[i]);
    }
    return 0;
}

0
投票

您可以这样分配它:

char** array=(char **)malloc(sizeof(char*)*x); //x-how many strings u want to have in array

然后您要为每个字符串分配一个当您想释放已分配的内存时,您应该这样做:

void destroy(char** array){
if(array != NULL){ //just to be safe
for(int i=0;;i++){
if(*(array+i)==NULL) break;
free(*(array+i));}
}
free(array);}
© www.soinside.com 2019 - 2024. All rights reserved.