首先,对不起,如果我的问题已经被回答了。我找到了一些(在某种程度上)相似的线索,但我没能解决我的问题。
其次,我是C语言中的单链表新手,所以如果你能尽可能简单地回答我的问题,我会很高兴的。
我制作了一个简单的链接列表,其中包含以下字符:
#include <stdio.h>
#include <stdlib.h>
// declaration of node
struct _Node_
{
char data_string;
struct _Node_ *next;
};
int main() {
//a simple linked list with 3 Nodes, Create Nodes
struct _Node_* head = NULL;
struct _Node_* second = NULL;
struct _Node_* third = NULL;
//allocate 3 Nodes in the heap
head = (struct _Node_*)malloc(sizeof(struct _Node_));
second = (struct _Node_*)malloc(sizeof(struct _Node_));
third = (struct _Node_*)malloc(sizeof(struct _Node_));
// assign data for head
head->data_string = 'H'; //assign value according struct
head->next = second; //points to the next node
// assign data for second
second->data_string = 'E';
second->next = third;
third->data_string = 'Y';
third->next = NULL;
return 0;
}
链接列表现在看起来如下:
/* Linked list _Node_
head second third
| | |
| | |
+---+---+ +---+---+ +----+------+
| 1 | o-----> | 2| o-------> | 3 | NULL |
+---+---+ +---+---+ +----+------+
*/
假设我有3个数组,如下所示:
char name1[] = "Joe";
char name2[] = "Eve";
char name3[] = "Brad";
我的目标是将这个数组复制到每个数据字段中,结果如下:
/* Linked list _Node_
head second third
| | |
| | |
+-----+---+ +-------+---+ +-------+------+
| Joe | o-----> | Eve | o-----> | Brad | NULL |
+-----+---+ +-------+---+ +-------+------+
*/
我怎样才能做到这一点?我已经尝试添加/更改以下内容:
...
struct _Node_
{
char data_string[8];
struct _Node_ *next;
};
...
...
char name1[] = "Joe";
char name2[] = "Eve";
char name3[] = "Brad";
// assign data for head
head->data_string = name1; //assign value according struct
head->next = second; //points to the next node
// assign data for second
second->data_string = name2;
second->next = third;
third->data_string = name3;
third->next = NULL;
...
但编译之后我得到的是:
stack_overflow.c:27:23: error: array type 'char [8]' is not assignable
head->data_string = name1; //assign value according struct
~~~~~~~~~~~~~~~~~ ^
stack_overflow.c:31:25: error: array type 'char [8]' is not assignable
second->data_string = name2;
~~~~~~~~~~~~~~~~~~~ ^
stack_overflow.c:34:24: error: array type 'char [8]' is not assignable
third->data_string = name3;
~~~~~~~~~~~~~~~~~~ ^
3 errors generated.
也许有人能帮忙,我很感激。
再次,如果这是重复的,很抱歉,但我不能用其他线程解决这个问题。。
最佳答案
您需要一个代码示例:
struct Node
{
char *data_string;
struct Node *next;
};
struct Node *newNode (char *s)
{
struct Node *node;
if (!s) return 0; // error: no string
if (!(node= malloc(sizeof(struct Node)))) return 0; // no more memory
node->data_string= malloc(strlen(s)+1);
if (!node->data_string) {
free(node);
return 0;
}
strcpy(node->data_string,s);
node->next= 0;
return(node);
}
void freeNode(struct Node *node)
{
if (!node) return;
if (node->data_string) free(node->data_string);
free(node);
}
笔记:
因为C中的字符串有一个空的终止字符,所以为字符串1分配的内存超过了长度。
不要在标识符名称前使用下划线-它们是为编译器保留的。
不要投射
malloc
的结果。它返回一个void
指针,该指针与任何指针类型兼容。此示例包括所有必需的错误检查。