【发布时间】:2020-04-07 22:51:32
【问题描述】:
我必须创建一个程序,该程序具有一组客户(包含名称、代码和文档的结构)以及按代码顺序插入、删除和列出所有这些的函数。我不明白我应该做什么。请注意insertCostumer、removeCostumer和listCostumer的参数不能更改。
代码01:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#define MAX_REG 10
typedef struct _costumer {
int code;
char name[50];
char documentation[20];
} costumer;
代码02:
int main(int argc, char** argv) {
costumer *costumers[MAX_REG];
costumer **p_costumer;
p_costumer = &costumers[0];
int count = 0;
memset(costumers, 0, sizeof(costumers));
//Some code to check what to do using a switch
case '1': insertCostumer(p_costumer, &count); getch(); break;
case '2': removeCostumer(p_costumer, &count); getch(); break;
case '3': listCostumers(p_costumer, &count); getch(); break;
//Some code
return (EXIT_SUCCESS);
}
代码03:
void insertCostumer(costumer **p_costumer, int *count){
char aux[50];
char aux2[20];
if(*count < MAX_REG) {
*p_costumer = (costumer *) malloc(sizeof(costumer));
printf("\nInsert the code: ");
gets(aux);
(*p_costumer)->code = atoi(aux);
printf("Insert the name: ");
gets(aux);
strcpy((*p_costumer)->name, aux);
printf("Insert the documentation: ");
gets(aux2);
strcpy((*p_costumer)->documentation, aux2);
(*count)++;
p_costumer = &*p_costumer[*count];
} else {
printf("List full! Remove a costumer first!\n");
}
}
void removeCostumer(costumer **p_costumer, int *count){
char aux3[50];
int cod;
printf("\nInsert the code of the costumer to be removed: ");
gets(aux3);
cod = atoi(aux3);
for(int i = 0; i < *count; i++) {
if(p_costumer[i]->code == cod) {
strcpy(p_costumer[i]->name, NULL);
p_costumer[i]->code = 0;
strcpy(p_costumer[i]->documentation, NULL);
}
}
}
void listCostumers(costumer **p_costumer, int *count){
for(int i = 0; i < *count; i++) {
printf("Code: %d | Name: %s | Documentation: %s\n", p_costumer[i]->code, p_costumer[i]->name, p_costumer[i]->documentation);
}
}
我不知道我做错了什么;老实说,没有任何工作。我试图先插入、列出和删除,然后再尝试进行排序部分,但我什至无法完成这部分。例如,当我列出时,仅列出最后添加的客户。
有人可以帮我吗?
【问题讨论】:
-
你不能改变[各种]函数的参数吗?如果这是一项学校作业,那么您的教师正在教您如何糟糕地编写代码。这些函数应该采用一个指向 [new] “list” 结构的指针,该结构具有 both 基本数组指针 和 计数(例如)
struct list { costumer *base; int count; };这简化了设计和提高可靠性。 强制你使用双层指针只是不好的做法。 -
我认为他希望我们以这种方式使用它,以便我们了解它是如何工作的。有没有办法做到这一点?谢谢!
标签: c arrays function pointers pointer-to-pointer