我有这个基本的链表结构:
struct node
{
char *name;
float salary;
struct node *nextNode;
};
struct list
{
struct node *firstNode;
};这是我的insert功能:
void insert(struct list *pList, char *newName, float newSalary)
{
struct node *newNode;
newNode = (struct node *)malloc(sizeof(struct node));
newNode->salary = newSalary;
newNode->name = newName;
if (pList->firstNode == NULL)
{
pList->firstNode = newNode;
newNode->nextNode = NULL;
}
else
{
struct node *pos = pList->firstNode;
for(; pos->nextNode; pos = pos->nextNode);
pos->nextNode = newNode;
newNode->nextNode = NULL;
}
}这是我的main():
int main(void)
{
struct list lst;
struct list *plst = &lst;
createList(plst); //initializes the list
char name1[] = "John";
char name2[] = "Thomas";
char name3[] = "Albert";
insert(plst, name1, 1000);
insert(plst, name2, 2000);
insert(plst, name3, 3000);
}除了char数组的传输之外,一切都很好。我认为传递char数组的最好方法是将指针传递给char数组中的第一个char,但我看不到我做错了什么。
另外,最好先创建一个新的node,然后将一个指向这个node的指针传递给insert函数?它是相似的,但也许更可接受?