通过函数的参数将字符串存储在结构中

Storing a string in struct via an argument to a function

我正在努力弄清楚如何将字符串传递给函数,然后如何通过指针将其存储在结构中。我想创建一个链表,其中每个节点包含一个节点名称(字符串)和数据(整数),代表到达该节点所需的权重。

表示节点的结构如下:

struct ListNode
{
    // The energy required to reach in this node
    int data;
    // The name of the node
    char location[20];

    // And the nodes along side this one
    struct ListNode* next;
    struct ListNode* prev;
};

以下函数生成一个节点并设置其下一个和上一个指针:

// Allocate a new listNode with the provided value
struct ListNode* listNodeConstructor(int value, char *city)
{
    struct ListNode* newNode;

    // Reserve memory for a node
    newNode = malloc(sizeof(struct ListNode));

    // Set its values
    newNode->data = value;
    newNode->name = strdup(city); /* This is how I've tried to implement it but it causes an error */
    newNode->next = NULL;
    newNode->prev = NULL;

    // And return it
    return newNode;
}

如果有人能告诉我如何在节点结构中正确存储字符串,我将永远感激不已。

strdup() 将字符串复制到堆中新分配的位置,并 returns 指向新字符串的指针。

请注意,您还需要 free 它。

问题是,您要设置的字符串是结构的一部分,而不仅仅是您可以设置的指针。

您有两个选择:

  • 使用 strcpy(newNode->name,city); 而不是 newNode->name = strdup(city);。这会将城市字符串复制到 newNode 但您需要确保 city 具有 [=16=] 直到 newNode->name 溢出。

  • name更改为只是一个指针,并在释放节点时释放它。在这种情况下,您可以使用 strdup。 (将 char location[20]; 更改为 char *location;

您正试图通过以下方式使用 strdup (3) which creates a copy of the string in a newly heap allocated space. You are therefore attempting to assign a pointer (which is the return of your strdup to a char array. As you already have allocated your string space in your structure, you should therefore use strcpy (3)strcpy(newNode->name, city).

另请注意,当您不打算修改它们时,将指针参数作为 const 传递始终是一个好习惯。此约定旨在提高可读性,当您希望在程序变大时对其进行调试时非常有帮助。

你不能给数组赋值。您只能分配标量变量或结构或联合

struct ListNode
{
    // The energy required to reach in this node
    int data;
    // The name of the node
    char *name;
    char name1[32];
    struct ListNode* next;
    struct ListNode* prev;
};

int foo(struct ListNode *node, const char *str)
{
    node -> name = str; // but remember that it only assigns the 
                        //reference and does not copy the string
    /* OR */
    node -> name = strdup(str); // but remember to free it
    strcpy(node -> name1, str);
}