【问题标题】:Node in linked-list in C languageC语言链表中的节点
【发布时间】:2021-07-06 19:05:40
【问题描述】:

我开始学习链表。 我的问题是条件语句不起作用。这是问题代码。

'''
Node* search_word(Node* head, Word target)
{
Node*p=head;
while(p != NULL)
{
    if(p->data.name==target.name)
    {
        printf("%s founded", target.name);
        return p;
    };
    p=p->nextNodeAddress;
};
printf("There is no %s. \n", target.name);
return NULL;
}

'''

这是我的完整源代码。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

# 创建名为 Word 的结构体,其字符名称为 [100]

typedef struct Word 
{
    char name[100];
} Word;

# 创建名为 Node 的结构体

typedef struct node
{
 
Word data;

struct node* nextNodeAddress;
} Node;

# 可以将节点插入列表第一个的函数

Node* insert_first(Node*head, Word newData)
{
    Node* p=(Node*)malloc(sizeof(Node));
    p->data = newData;
    p->nextNodeAddress=head;
    head=p;
    return head;
};

#可以打印出列表的函数

void print_listedNode(Node* head)
{
    for(Node* i=head; i!=NULL; i=i->nextNodeAddress)
    {
        printf("%s->", i->data.name);
    };
    printf("NULL\n");
}

# 可以搜索单词的函数(条件语句不起作用。但没有错误。)

Node* search_word(Node* head, Word target)
{
    Node*p=head;
    while(p != NULL)
    {
        if(p->data.name==target.name)
        {
            printf("%s founded", target.name);
            return p;
        };
        p=p->nextNodeAddress;
    };
    printf("There is no %s. \n", target.name);
    return NULL;
}

# int main()

int main(int argv, char* argc)

{
    Node* head = NULL;
    Word data;

strcpy(data.name, "APPLE");
head = insert_first(head, data);
print_listedNode(head);

strcpy(data.name, "LEMON");
head = insert_first(head, data);
print_listedNode(head);

strcpy(data.name, "BANANA");
head = insert_first(head, data);
print_listedNode(head);

strcpy(data.name, "BANANA");
head = search_word(head, data);
print_listedNode(head);
return 0;
}

结果是

APPLE->NULL
LEMON->APPLE->NULL
BANANA->LEMON->APPLE->NULL
There is no BANANA.
NULL

我希望得到

 APPLE->NULL
 LEMON->APPLE->NULL
 BANANA->LEMON->APPLE->NULL
 BANANA founded
 BANANA->LEMON->APPLE->NULL

感谢您阅读令人眼花缭乱的代码。

【问题讨论】:

  • 您正在使用p-&gt;data.name==target.name,这在C 中不起作用。它会比较那里的指针。使用函数strncmp
  • @Hrant 不,应该在这里使用strcmp 而不是strncmp

标签: c string-comparison c-strings function-definition


【解决方案1】:

在这个if语句中

if(p->data.name==target.name)

比较两个指针(在数组指示符隐式转换为指向它们的第一个元素的指针之后)而不是指针指向的字符串。

你需要写

if( strcmp( p->data.name, target.name ) == 0 )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-07
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多