我正在尝试编写一个代码,该代码将文本文件读取到链接列表并存储在内存中。我不知道为什么在我的代码中使用malloc
函数时会出现错误。
这是预先给定的头文件,需要保持原样:
#ifndef ADDRESSBOOK_LIST_H
#define ADDRESSBOOK_LIST_H
#define NULL_SPACE 1
#define NAME_LENGTH (20 + NULL_SPACE)
#define TELEPHONE_LENGTH (10 + NULL_SPACE)
typedef struct telephoneBookNode
{
int id;
char name[NAME_LENGTH];
char telephone[TELEPHONE_LENGTH];
struct telephoneBookNode * previousNode;
struct telephoneBookNode * nextNode;
} TelephoneBookNode;
typedef struct telephoneBookList
{
TelephoneBookNode * head;
TelephoneBookNode * tail;
TelephoneBookNode * current;
unsigned size;
} TelephoneBookList;
这是我编写的用于将txt文件加载到内存中的代码:
entry
的格式ID, Name, Number
与123, Alice, 0123456789
#include "addressbook_list.h"
TelephoneBookList * createTelephoneBookList(char entry[])
{
TelephoneBookList* aList = NULL;
TelephoneBookNode* aNode = createTelephoneBookNode();
char *tokens;
tokens = strtok(entry, ", ");
aNode->id = tokens;
tokens = strtok(NULL, ", ");
aNode->name = tokens; //Error: array type char[21] is not assignable
tokens = strtok(NULL, ", ");
aNode->telephone = tokens; //Error; array type char[11] is not assignable
aNode->nextNode = aList->head;
aList->head = aNode;
if (aList == NULL)
{
aNode->nextNode = NULL;
aNode->previousNode = NULL;
aList->current = aNode;
aList->head = aNode;
aList->tail = aNode;
}
else
{
aList->tail->nextNode = aNode;
aNode->nextNode = NULL;
aList->tail = aList->tail->nextNode;
}
return aList;
}
这是创建节点的功能,我收到错误:
与整数转换不兼容的指针分配给' char'来自' char *',用*
取消引用
TelephoneBookNode * createTelephoneBookNode()
{
TelephoneBookNode* aNode;
aNode = (TelephoneBookNode*) malloc(sizeof aNode);
aNode->id = (int) malloc(sizeof aNode->id);
aNode->name = (char*) malloc(sizeof aNode->name);
aNode->telephone = (char*) malloc(sizeof aNode->telephone);
return aNode;
}
请有人能就错误向我解释一下。非常感谢你!
答案 0 :(得分:4)
malloc()
in C。=
运算符的操作数时,数组将转换为非左值指针。TelephoneBookNode
有两个指针和一些其他成员,但是你只为一个指针分配空间。这将在典型环境中带来空间和超出范围的运气。您的createTelephoneBookNode()
功能应该是这样的:
TelephoneBookNode * createTelephoneBookNode()
{
TelephoneBookNode* aNode;
/* add dereference operator to get the size of what will be pointed by aNode */
aNode = malloc(sizeof *aNode);
/* do initialization of member if it is required */
return aNode;
}
strcpy()
中可以使用 string.h
函数来复制字符串,atoi()
中可以使用stdlib.h
函数将字符串转换为整数。使用这些,为成员分配数据的部分应该是这样的:
tokens = strtok(entry, ", ");
aNode->id = atoi(tokens);
tokens = strtok(NULL, ", ");
strcpy(aNode->name, tokens);
tokens = strtok(NULL, ", ");
strcpy(aNode->telephone, tokens);
请注意,此处省略了错误检查。添加它们以使程序更安全。
答案 1 :(得分:0)
您不需要malloc来执行以下操作:
aNode->id = (int) malloc(sizeof aNode->id);
aNode->name = (char*) malloc(sizeof aNode->name);
aNode->telephone = (char*) malloc(sizeof aNode->telephone);
因为在您声明内存时已经分配了内存。 您只需要为链接列表节点分配内存,例如:
TelephoneBookNode * createTelephoneBookNode()
{
Telephonenter code here`eBookNode* aNode;
aNode = (TelephoneBookNode*) malloc(sizeof aNode);
return aNode;
}
答案 2 :(得分:0)