C - 动态内存分配的2d字符串数组

时间:2018-05-05 18:59:55

标签: c arrays

我最近遇到了一个问题,我试图重新分配内存 一个二维char数组,但它似乎不起作用。 在这里,我试图通过数组原因重新分配原因的数量 将原因数和char数组(字符串)的大小相乘,但它不起作用,2d数组原因仍然有1个单元格。提前谢谢!

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

#define STR_LEN 50

typedef struct list
{
    char** reasons;
    int numReasons;
}list;

void printReasons(list* pCons, list* pPros,int conNum,int proNum);

int main(void)
{
    list proList = { 0, 1 };
    list conList = { 0, 1 };
    char dillema[STR_LEN] = { 0 };
    char stringHelper[STR_LEN] = { 0 };
    int flag = 1, choice = 0;

    conList.reasons = (char**)malloc(sizeof(char*));
    proList.reasons = (char**)malloc(sizeof(char*));

    printf("What is your dillema?\n");
    fgets(dillema, STR_LEN,stdin);

    do
    {
        printf("Choose option:\n1 - Add PRO reason\n2 - Add CON reason\n3 - print reasons\n4 - Exit\n");
        scanf("%d", &choice);
        getchar();
        switch (choice)
        {
        case 1:
            printf("Enter a reason to add to a list PRO:");
            fgets(stringHelper, STR_LEN, stdin);
            stringHelper[strlen(stringHelper) - 1] = 0;

            proList.reasons = (char**)realloc(proList.reasons,sizeof(char*) * proList.numReasons);
            proList.reasons[proList.numReasons - 1] = (char*)malloc(sizeof(char) * strlen(stringHelper));

            strcpy(proList.reasons[proList.numReasons - 1], stringHelper);
            proList.numReasons++;
            break;
        case 2:
            printf("Enter a reason to add to a list CON:");
            fgets(stringHelper, STR_LEN, stdin);
            stringHelper[strlen(stringHelper) - 1] = 0;

            conList.reasons = (char**)realloc(conList.reasons,sizeof(char**) * conList.numReasons);
            conList.reasons[conList.numReasons - 1] = (char*)malloc(sizeof(char) * strlen(stringHelper));

            strcpy(conList.reasons[conList.numReasons - 1], stringHelper);
            conList.numReasons++;
            break;
        case 3:
            printReasons(&conList, &proList,conList.numReasons,proList.numReasons);
            break;
        case 4:
            flag = 0;
            break;
        default:
            printf("choice is not valid,choose again:\n");
        }
    } while (flag);


    getchar();  
    return 0;
}

void printReasons(list* pCons, list* pPros, int conNum, int proNum)
{
    int i = 0;
    for (i = 0; i < conNum; i++)
    {
        printf("%s\n",pCons->reasons[i]);
    }
    for (i = 0; i < proNum; i++)
    {
        printf("%s\n", pPros->reasons[i]);
    }
}

0 个答案:

没有答案