【问题标题】:I can't store a string of characters in a node of linked list我无法在链表的节点中存储字符串
【发布时间】:2016-01-01 16:05:30
【问题描述】:

我正在完成有关机场模拟的课程作业,但在尝试将信息存储在字符数组部分时遇到了一些麻烦。

我应该输入一个字符串,它将存储在节点的planeName 部分,但它似乎无法工作。我的int main() 现在几乎是空的,因为我不想继续使用不正确的函数进行编码。

以下是我的代码:

struct node {
    char planeName[5];
    int planeNumber;
    struct node* next;
}; 

struct node* front = NULL;
struct node* rear = NULL;

void Enqueue(char name[5], int x);

int main() {

}

void Enqueue(char name[5], int x){

    struct node* temp = (struct node*)malloc(sizeof(struct node));

    temp -> planeName = name; 
    temp -> planeNumber = x;
    temp -> next = NULL;

    if (front == NULL && rear == NULL)
        front = rear = temp;
    rear -> next = temp; //set address of rear to address of temp
    rear = temp; //set rear to point to temp

    return;
}

This is the error message 在包含以下内容的行中:temp -> planeName = name

这是弹出错误消息的部分,我不知道为什么会发生这种情况。

如果我的问题不够清楚,有人可以帮我问更多问题吗?

【问题讨论】:

    标签: c linked-list


    【解决方案1】:
    temp -> planeName = name;
    

    您不能分配给数组。数组不能用作左值。请改用strcpy-

    strcpy(temp -> planeName,name);
    

    注意- 但请确保您的 char 数组在将它们传递给 strcpy 之前是 nul 终止的。

    【讨论】:

    • 嗨!原谅我的无知,但是什么是 nul 终止的?我是一个相当新的程序员,因此我不确定一些技术术语。
    • @KateLee I would suggest you to take a look here. 。这将在 NULLNUL 之间清除。
    【解决方案2】:

    您的字符串是字符数组,因此您必须复制各个元素。幸运的是,有一些函数(如 strcpy)可以做到这一点。

    【讨论】:

      【解决方案3】:

      错误来自您通过复制数组名称planeName 来执行浅复制

      如果要复制数组,则需要复制其中的每个元素,如果数组的最后一个元素包含指示其结束的特殊字符,例如字符 \0,则这样做会更容易。

      一个包含最后一个字符\0 的数组被称为:null 终止。有很多函数可以对以空结尾的数组执行操作。您需要的是:

      char * strcpy ( char * destination, const char * source );
      

      这会将作为source 传递的空终止数组的所有元素复制到destination。在您的情况下,它将如下所示:

      strcpy(temp -> planeName,name);
      

      这里是关于strcpy()的简要信息。

      【讨论】:

      • 谢谢!这个回答很详细!一个问题,听起来可能很傻,但我必须在输入中明确写 '\0' 吗?
      • @KateLee 不,如果您使用scanf 输入,那么语句可能是scanf("%4s",name);,如果您使用fgets,它将自动添加到name
      • @Kate Lee 很高兴我能帮上忙!
      • @ameyCU 感谢您的澄清!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多