c - 如何将字符串存储在链表的节点内?我正在使用 Visual Studio。

标签 c

我将动态分配的字符串从 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/

相关文章:

c - EVP 读取 PEM 私钥无法正常工作

c - 使用静态指针的动态内存分配

c - && 在 C 编程语言中的行为

c - kill() 函数在 C 语言中不起作用

c - 为什么第 22 行是必需的?

c - 使用长的位列表

C malloc,重新分配。如何从数组中删除单个元素。

c - ANSI C - 使用 typedef 将替代名称分配给指针类型的好处

c - 在 C 中使用 Strtok 获取字符串

c - rewind() 到底做了什么?