【发布时间】:2017-02-22 03:57:18
【问题描述】:
在使用 C 中的结构时,我真的很难理解在使用 malloc 和 realloc 时实际发生的情况。我正在尝试解决电话簿问题,我必须创建一个可以添加、删除、并显示条目。可以有无限数量的条目,所以我必须动态定义我的结构数组。我的删除功能还必须找到所需的条目,之后移回所有条目,然后使用realloc 释放最后一个条目。我认为这就是对realloc 的基本了解对我真正有帮助的地方。
我认为我可以正常工作的唯一部分是添加功能,我仍然不知道我是否正确设置了它 - 我只知道它在我运行时可以正常工作。如果有人在非常基本的水平可以帮助我,我将不胜感激。
这是我乱七八糟的代码:-(
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getEntry(int *);
typedef struct person {
char fname[20];
char lname[20];
int number[10];
}person;
void getInfo(int *,int,person*);
void delInfo(int*,int,person*);
void showInfo(int*,int,person*);
int main(){
int a=0;
int i=0;
int con=0;
person* contacts=(person*)malloc(sizeof(person));
person* pcontacts;
pcontacts=(person*)calloc(0,sizeof(person));
getEntry(&a);
while (a!=4){
switch (a){
case 1:
pcontacts=(person*)realloc(pcontacts,con* sizeof(person));
getInfo(&con,i,contacts);
break;
case 2:
delInfo(&con,i,contacts);
break;
case 3:
showInfo(&con,i,contacts);
break;
default:
printf("\n Error in response. Please try again: ");
break;
}
getEntry(&a);
}
printf("\n Thank you for using the Phone Book Application!\n\n");
free(contacts);
return 0;
}
void getEntry(int *a1){
int b;
printf("\n\n\n Phone Book Application\n\n 1) Add Friend\n 2) Delete Friend\n 3) Show Phone Book Entries\n 4) Exit\n\n Make a selection: ");
scanf("%d",&b);
*a1 = b;
}
void getInfo(int *con,int i,person*contacts){
printf("\n Enter first name: ");
scanf("%s",contacts[*con].fname);
printf(" Enter last name: ");
scanf("%s",contacts[*con].lname);
printf(" Enter telephone number without spaces or hyphens: ");
scanf("%d",contacts[*con].number);
(*con)++;
printf("\n Entry Saved.");
}
void delInfo(int *con,int i,person*contacts){
char delfirst[20];
char dellast[20];
printf("\n First Name: ");
scanf("%s",delfirst);
printf(" Last Name: ");
scanf("%s",dellast);
for (i=0; i<*con;i++){
if (delfirst==contacts[i].fname && dellast==contacts[i].lname){
}
}
}
void showInfo(int *con,int i,person*contacts){
char nullstr[1]={"\0"};
if (*con>0){
printf("\n Current Listings:\n");
for (i=0;i<*con;i++){
if (strcmp(nullstr,contacts[i].fname)!=0){
printf(" %s %s %i\n",contacts[i].fname,contacts[i].lname,contacts[i].number);
}
else {};
}
}
else {
printf("\n No Entries\n");
}
}
【问题讨论】:
-
如果您想要评论,请将其带到codereview.stackexchange.com 如果没有,您的问题是什么?
-
reallocdocumentation 的哪一部分你不明白? -
附带说明:将
typedef命名为p不是很明智。为什么不typedef struct person { char fname[20]; char lname[20]; int number[10]; } person; -
con在case 1中首次使用时为零,因此 that 对调整大小来说不是好兆头,并导致 未定义的行为 再往前走。也绝对没有理由将i作为参数向下发送,也没有任何理由通过地址将con传递给showInfo。您还忽略了包含<string.h>,这是正确声明strcmp所必需的。