【问题标题】:deleting all entries of a linked list in c, error删除c中链表的所有条目,错误
【发布时间】:2021-12-09 02:28:29
【问题描述】:

所以,我试图在我的电话簿实验室中删除链接列表的所有条目,它正在读取一个我不知道如何修复的错误。错误是读取“从类型'int'分配给类型char [50]时不兼容的类型。”

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
    
typedef struct phonebook{ 
    char first_name[70];
    char last_name[50];
    char phone_num[50];
    }entry; //TypeDef to modify structure name


    void addFriend(entry *, int *); //function prototype to add a friend 
    void dltFriend(entry *, int *, int);
    void showBook(entry *, int *);
    void alphaList(entry*, int*);
    void findNum(entry*, int*);
    void randSelect(entry*, int*);
    void dltAll(entry*,int*);

void dltAll(entry*phonebook, int*count){
int i;
for(i=0; i< *count; i++)
{

    do{
        phonebook[i].first_name = '\0';
        phonebook[i].last_name = '\0';
        phonebook[i].phone_num = '\0';
        break;
    }
    while (i <= *count);

}
printf("\nAll contacts deleted\n");
system("pause");
}

【问题讨论】:

  • 您不能为任何数组分配新值。如果要为每个字符数组分配一个 nul 终止符。您需要使用数组索引:phonebook[i].first_name[0] = '\0'。其他数组也一样。
  • 这样可以,但它只是清除条目而不是删除它们,有没有办法解决这个问题。谢谢!
  • @galapagos 你不能删除这些条目。您唯一能做的就是将它们标记为已删除。如果你想真正删除它们,你需要研究动态内存分配,但这可能还为时过早。
  • do-while 循环的目的是什么?
  • for 循环中的while循环有一个break,很奇怪

标签: c linked-list null phonebook


【解决方案1】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

typedef struct phonebook{
    char first_name[70];
    char last_name[50];
    char phone_num[50];
    }entry; //TypeDef to modify structure name


    void addFriend(entry *, int *); //function prototype to add a friend
    void dltFriend(entry *, int *, int);
    void showBook(entry *, int *);
    void alphaList(entry*, int*);
    void findNum(entry*, int*);
    void randSelect(entry*, int*);
    void dltAll(entry*,int*);

void dltAll(entry*phonebook, int*count){
int i;
for(i=0; i< *count; i++)
{
        strcpy(phonebook[i].first_name,"NULL");
        strcpy(phonebook[i].last_name,"NULL");
        strcpy(phonebook[i].phone_num,"NULL");
}
printf("\nAll contacts deleted\n");
}
/*int main()
{
    void dltAll();
return 0;
}*/

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

错误是读取“从类型'int'分配给类型char [50]时不兼容的类型。”

消息是由于这一行:

phonebook[i].last_name = '\0';
\____________________/   \__/
 This is a char[50]       This is an integer

将整数值分配给数组是没有意义的。如果你想把last_name 变成一个空字符串:

phonebook[i].last_name[0] = '\0';

其他说明:

类似的构造:

do{
    ...
    break;
}
while (i <= *count);

没有意义,因为break 将在执行一次... 后结束循环。所以只需删除循环。

我还希望该函数将*count 设置为零。

【讨论】:

  • 好的,这很有帮助,我明白为什么这是有道理的。谢谢!
猜你喜欢
  • 2012-08-18
  • 2013-04-24
  • 1970-01-01
  • 2012-04-07
  • 1970-01-01
  • 1970-01-01
  • 2016-08-27
  • 1970-01-01
  • 2023-04-01
相关资源
最近更新 更多