0

我有这个基本的链表结构:

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然后将指向 this 的指针传递nodeinsert函数会更好吗?它很相似,但也许更容易接受?

4

2 回答 2

2
newNode->name = newName;

这不是复制 c 字符串的正确方法。使用strcpystrncpy

strcpy(newNode->name,newName);

正如@Pablo 指出的那样,您没有为字符串分配内存,因此首先分配然后复制:

newNode->name = malloc(strlen(newName)+1);
strcpy(newNode->name,newName);
于 2012-09-29T11:38:25.427 回答
0

代码对我来说似乎很好。但是,除了 char 数组的传输之外,您所说的效果很好是什么意思?您是否收到错误、段错误、意外情况,如果有,那是什么?

于 2012-09-29T11:39:15.657 回答