java中动态内存_在c中结构中动态分配内存

有很多问题 . 以前的评论和答案仍然适用 .

这是一个干净的解决方案 .

列表结构现在是自包含的,无需跟踪单独变量中的字符串数

添加了自包含 AddString 函数

不再需要 malloc

正确释放所有已分配的内存

删除了一些逻辑错误( keepGoing 的反转逻辑)

仍有改进的余地 . 特别是没有错误检查内存分配功能 .

#include

#include

#include

typedef struct list {

int size; // number of strings

int chunksize; // current of chunk

char ** reason;

} list;

void printMenu();

void printList(list * reasons);

void freeList(list * l);

void AddString(list *l, const char *string);

int main(void)

{

int keepGoing = 1;

int choice = 0;

list pros = { 0 }; // = {0} initializes all fields to 0

list cons = { 0 };

while (keepGoing) {

printMenu();

scanf("%d", &choice);

char input[50];

fgets(input, sizeof(input), stdin); // absorb \n from scanf

switch (choice) {

case 1:

printf("Enter a reason to add to list PRO: ");

fgets(input, sizeof(input), stdin);

AddString(&pros, input); // Add string to pros

break;

case 2:

printf("Enter a reason to add to list CONS: ");

fgets(input, sizeof(input), stdin);

AddString(&cons, input); // Add string to cons

break;

case 3:

printf("PROS:\n");

printList(&pros);

printf("CONS:\n");

printList(&cons);

break;

case 4:

keepGoing = 0;

break;

default:

printf("Invalid value.");

keepGoing = 1;

}

}

freeList(&pros);

freeList(&cons);

getchar();

return 0;

}

#define CHUNKSIZE 10

void AddString(list *l, const char *string)

{

if (l->size == l->chunksize)

{

// resize the reason pointer every CHUNKSIZE entries

l->chunksize = (l->chunksize + CHUNKSIZE);

// Initially l->reason is NULL and it's OK to realloc a NULL pointer

l->reason = realloc(l->reason, sizeof(char**) * l->chunksize);

}

// allocate memory for string (+1 for NUL terminator)

l->reason[l->size] = malloc(strlen(string) + 1);

// copy the string to newly allocated memory

strcpy(l->reason[l->size], string);

// increase number of strings

l->size++;

}

void freeList(list * l) {

for (int i = 0; i < l->size; i++) {

// free string

free(l->reason[i]);

}

// free the list of pointers

free(l->reason);

}

void printList(list * l) {

for (int i = 0; i < l->size; i++) {

printf("%s\n", l->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");

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值