节点,按值传递,C中奇怪的字符串行为

时间:2012-08-26 15:45:42

标签: c string

所以我有一个自制的双链表实现,它被用作排队的替代品。 (用C语言实现,我认为这种语言很弱)。

我的节点的typedef:

typedef struct Node
{
    char *name;
    int data;
    int recurring;
    struct Node *next;
    struct Node *prev;
}node;

表示“一个节点有一个名称,一个数据点,是否重现,以及指向前一个和下一个节点的指针”

插入功能如此

node * insertFromTail(node *tail, int data, int recurring, char *name)
{
    node *newNode;
    node *oldNext;
    node *origTail = tail;
    /*assume *pointer points to tail of list*/
    /*printf("tail data is %d\n", tail->data);
    printf("before loop\n");*/
    while(tail->prev != NULL && tail->data > data)
    {
        /*printf("inside while loop\n");*/
        tail = tail -> prev;
    }
    /*printf("after loop\n");*/
    /*if we are looking at a no item list or tail*/
    if(tail->next == NULL)
    {
        /*printf("pointer is tail\n");*/
        return insert(tail, data, recurring, name);
    }
    else /*tail pointer points at item before the point of insertion*/
    {
        /*printf("default case\n");
        printf("pointer data is %d\n", tail->data);*/
        oldNext = tail->next;
        newNode = (node *)malloc(sizeof(node));
        newNode->data = data;
        newNode->recurring = recurring;
        newNode->name = name;
        oldNext -> prev = newNode;
        newNode -> next = oldNext;
        tail -> next = newNode;
        newNode -> prev = tail;
        return origTail;
    }
}

使用内部插入

node * insert(node *tail, int data, int recurring, char *name)
{
        /* Allocate memory for the new node and put data in it.*/
        tail->next = (node *)malloc(sizeof(node));
        (tail->next)->prev = tail;
        tail = tail->next;
        tail->data = data;
        tail->recurring = recurring;
        tail->name = name;
        tail->next = NULL;
        return tail;
}

传递列表的尾部,数据点,下一个项目将重现的时间以及项目的名称。

如果我们从一个空的节点开始并且具有NULL prev和next引用(一个虚节点),并且我添加了三个具有ADD函数的唯一节点,该函数调用insertFromTail从stdIn获取输入

int main()
{
    node *start,*temp,*tail;
    start = (node *)malloc(sizeof(node));
    temp = start = tail;
    temp->next = NULL;
    temp->prev = NULL;
    if(strcmp(command, "ADD") == 0)
    {
        scanf("%d",&argTime);
        scanf("%s",&argName);
        tail = insertFromTail(head, argTime, 0, *argName);
    }
}

输入如下:

INPUT: 
ADD 10 Gin
ADD 20 Vodka
ADD 30 Rum
PRINT

我会得到

的输出
OUTPUT:
Rum 10
Rum 20
Rum 30

这是一个错误,因为所需的输出将是     OUTPUT:     杜松子酒10     伏特加20     朗姆酒30

我觉得它与字符串如何传递到节点有关,但正如你所看到的,我很难过。这是作业中留下的最后一件事,其他一切都完美无缺,所以我决定在这里询问是否有人可以在正确的道路上轻推我。感谢您的帮助:)

P.S。抱歉一切都很糟糕,我睡不着觉:(

1 个答案:

答案 0 :(得分:3)

简短回答:您需要复制该名称:

tail->name = strdup(name);

更长的答案:在每次迭代中,您都存储相同的指针。你正在存储它,然后在你下次再次写它时。因此,最终会得到3个相同的指针,指向您最后输入的内容。

一个简单的解决方法是复制字符串并存储副本:正是strdup所做的。但如果您的实施缺少strdup,您可以尝试:

tail->name = malloc(strlen(name) + 1);
strcpy(tail->name, name);
  • 不要忘记检查错误
  • 不要忘记free某些时候的记忆