gpt4 book ai didi

c - 使用动态内存分配 i C 时出现奇怪的输出

转载 作者:太空宇宙 更新时间:2023-11-04 06:23:13 25 4
gpt4 key购买 nike

我正在编写这段代码,但尚未完成。但是在测试添加新联系人功能和打印功能时,我得到了这个奇怪的输出。只要我不添加多个联系人,一切看起来都很好。我在这里做错了什么?

//Libraries:
#include <stdio.h>
#include <stdlib.h>

//Function prototypes
int showMenu(); //Shows user options

//Main function
int main() {

//Variable declerations
int i = 0;
int iOption = 0;
int iContacts = 0;
char *cPhoneBook_name;
int *iPhoneBook_nr;

cPhoneBook_name = (char *) calloc(1, 80 * sizeof(char));
iPhoneBook_nr = (int *) calloc(1, sizeof(int));

do {

//Memory check
if(cPhoneBook_name == NULL || iPhoneBook_nr == NULL){
printf("\nOut of Memory!\n");
return;
}

//Show menu
iOption = showMenu();

switch (iOption) {
case 1: //Add contact
printf("\nEnter name:\n");
scanf("%s", &cPhoneBook_name[iContacts]);
printf("\nEnter number:\n");
scanf("%d", &iPhoneBook_nr[iContacts]);
cPhoneBook_name = realloc(cPhoneBook_name, 80 * sizeof(char));
iPhoneBook_nr = realloc(iPhoneBook_nr, sizeof(int));
iContacts += 1;
break;
case 2: //Modify contact
//Code here
break;
case 3: //Show contacts
for(i = 0 ; i < iContacts ; i++) {
printf("\n%s %d\n", &cPhoneBook_name[i], iPhoneBook_nr[i]);
}
break;
case 4: //Free memory (delete contacts)
free(cPhoneBook_name);
free(iPhoneBook_nr);
break;
}
}while(iOption != 5);//Exit if iOption is 5;

system("clear");
return 0;
}


//Function definition - showMenu()
int showMenu() {

int iOption = 0;

//system("clear");

printf("\n Phone book \n");
printf("------------------------\n");
printf("1. Add new contact.\n");
printf("2. Edit existing contact\n");
printf("3. Show contact(s)\n");
printf("4. Clear phone book\n");
printf("5. Exit\n");
printf("------------------------\n");
printf("Option --> ");
scanf("%d", &iOption);

return iOption;
}
//---------------------------------------------------------

最佳答案

问题在于:

printf("\n%s %d\n", &cPhoneBook_name[i], iPhoneBook_nr[i]);

cPhoneBook_name 如果类型为 char[]。因此,例如表达式 char[1] 为您提供列表中的第二个字符。虽然代码中的名称是 80 个 char 宽。所以尝试:

printf("\n%s %d\n", &cPhoneBook_name[i*80], iPhoneBook_nr[i]);

编辑:

我还发现:

cPhoneBook_name = realloc(cPhoneBook_name, 80 * sizeof(char));

没有效果,因为您正在将 cPhoneBook_name 的大小从 80 调整到 80。尝试:

    cPhoneBook_name = realloc(cPhoneBook_name, (iContacts+1) 80 * sizeof(char)); 

还有: scanf("%s", &cPhoneBook_name[80*iContacts]);

关于c - 使用动态内存分配 i C 时出现奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30624227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com