通过函数的参数在struct中存储字符串
我正在努力弄清楚如何将字符串传递到函数中,然后如何通过指针将其存储在struct中。我想创建一个链表,其中每个节点都包含一个节点名(字符串)和表示到达该节点所需权重的数据(整数) 表示节点的结构如下所示:通过函数的参数在struct中存储字符串,c,linked-list,c-strings,C,Linked List,C Strings,我正在努力弄清楚如何将字符串传递到函数中,然后如何通过指针将其存储在struct中。我想创建一个链表,其中每个节点都包含一个节点名(字符串)和表示到达该节点所需权重的数据(整数) 表示节点的结构如下所示: struct ListNode { // The energy required to reach in this node int data; // The name of the node char location[20]; // And the
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()
将字符串复制到堆中新的malloced位置,并返回指向新字符串的指针
请注意,您还需要释放它
问题是,要设置的字符串是结构的一部分,而不仅仅是可以设置的指针
您有两个选择:
- 使用strcpy(newNode->name,city)代码>而不是
newNode->name=strdup(城市)代码>。这会将城市字符串复制到newNode
,但您需要确保city
具有\0
,直到newNode->name
溢出
- 将
name
更改为指针,并在释放节点时释放它。在这种情况下,您可以使用strdup
。(将字符位置[20];
更改为字符*位置;
您正试图使用它在新的堆分配空间中创建字符串的副本。因此,您正试图分配指针(这是将您的strdup
返回到char数组。由于您已经在结构中分配了字符串空间,因此应按以下方式使用:strcpy(newNode->name,city)
)
另外,请注意,当您不打算修改指针参数时,将其作为常量传递始终是一种很好的做法。此约定旨在提高可读性,并且在程序变大时要调试程序时非常有用。您不能分配数组。您只能分配标量变量、结构或联合
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);
}
您能否澄清/纠正结构中的位置
成员(定义中)与功能中的名称
成员之间的明显冲突?