有很多问题 . 以前的评论和答案仍然适用 .
这是一个干净的解决方案 .
列表结构现在是自包含的,无需跟踪单独变量中的字符串数
添加了自包含 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");
}