我将动态分配的字符串从 main.c
传递到函数 addNode()
作为指针 *str
。
我想将此字符串添加到我创建的节点中的字段中。
// Structure definitions
// Node in doubly-linked list
typedef struct DLN {
struct DLN *prev; // Pointer to previous list element
struct DLN *next; // Pointer to next list element
char *word;
} DLNode;
// Actual doubly-linked list
typedef struct {
DLNode *firstNode; // Pointer to first node in list
DLNode *lastNode; // Pointer to last node in list
} DLList;
// Function prototypes
void addNode(DLList *list, char *str);
void addNode(DLList *list, char *str) {
DLNode *newNode;
newNode = (DLNode*)malloc(sizeof(DLNode));
if (newNode == NULL) {
fprintf(stderr, "Error:Could not allocate new node\n");
exit(0);
}
//list is empty, add one node
if ((list->firstNode == NULL) && (list->lastNode == NULL)) {
list->firstNode = newNode;
list->lastNode = newNode;
newNode->next=NULL;
newNode->prev=NULL;
//(newNode->word)=*str;
//strncpy(newNode->word, , );???
}
最佳答案
为了让你的代码简单,在 DLNode 中将 word 声明为字符数组。说 char word[50]。
char word[50]; // in your DLNode structure
memset(newNode->word, '\0', sizeof(newNode->word)); // In addNode code
strcpy(newNode->word, str); // In addNode code
关于c - 如何将字符串存储在链表的节点内?我正在使用 Visual Studio。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43555679/