c - c中结构中的动态分配内存

标签 c pointers struct dynamic-memory-allocation realloc

我正在尝试创建两个列表,pros 和 cons,然后打印它们。 但我不知道我做错了什么。

我试着用gdb在线调试程序,发现错误在函数fgets()。

#include <stdio.h>
#include <string.h>
typedef struct list{
    char ** reason;

} list;
void printMenu();
void printList(list * myList, int len1);


int main(void)
{
    int keepGoing = 0;
    int choice = 0;
    int i = 0;
    int j = 0;
    list * pros;
    list * cons;

    while (!keepGoing){

        printMenu(); 
        scanf("%d", &choice);

        pros = (list*)malloc(sizeof(list));
        cons = (list*)malloc(sizeof(list));
        switch (choice){
        case 1:
            i++;
            printf("Enter a reason to add to list PRO: ");
            pros = (list*)realloc(pros, i*sizeof(list));
            fgets(pros->reason[i], 50, stdin);
            pros->reason[strcspn(pros->reason[i], "\n")] = 0;
            break;
        case 2:
            j++;
            cons = (list*)realloc(cons->reason, j*sizeof(list));
            printf("Enter a reason to add to list CON: ");
            fgets(cons->reason[j], 50, stdin);
            cons->reason[strcspn(cons->reason[j], "\n")] = 0;
            break;
        case 3:
            printf("PROS:\n");
            printList(pros, i);
            printf("CONS:\n");
            printList(cons, j);

            break;
        case 4:
            keepGoing = 1;
            break;
        default:
            printf("Invalid value.");
            keepGoing = 1;
        }
    }

    free(pros);
    free(cons);

    getchar();
    return 0;
}

void printList(list * reasons, int len1){
    int i = 0;
    for (i = 0; i < len1; i++){
        printf("%s\n", reasons->reason[i]);
    }
}
void printMenu(){
    printf("Choose option:\n");
    printf("1 - Add PRO reason\n");
    printf("2 - Add CON reason\n");
    printf("3 - Print reasons\n");
    printf("4 - Exit\n");
}

最佳答案

不需要动态分配这些:list * pros;列出 * 缺点;pros = (list*)realloc(pros, i*sizeof(list)); 这样的代码没有任何意义。

相反,将它们声明为普通变量。 列出专家

您需要动态分配的是成员 pros.reason。您需要分配一个它指向的指针数组,然后您需要分配各个数组。

关于c - c中结构中的动态分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43776959/

相关文章:

c - 内核空间中 PCI 内存的地址映射

C语言。数组左边框 [1..] 而不是 [0..]

c++ - 数据结构库供应商

c++ - 结构构造函数问题导致堆栈溢出

arrays - 如何将结构加载到数组中?

c - malloc的作用(正确使用malloc)

c - 如何将 C 指针递增 2

c++ - 如何从包含浮点值的字符数组中获取第一个元素?

c - 应用程序因指针、头文件和结构数组而崩溃

c - c中的类型声明和声明结构