Скопируйте массив в связанный список в каждом поле данных - PullRequest
0 голосов
/ 17 декабря 2018

Во-первых, извините, если на мой вопрос уже дан ответ.Я нашел некоторые темы, которые (в некотором роде) похожи, но я не смог решить мою проблему.Во-вторых, я новичок в single-link-list в C, поэтому я был бы рад, если бы вы могли ответить на мой вопрос как можно проще.

Я сделал простой linke-list, в котором есть символы:

#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.

Может быть, кто-то может помочь, я ценю любую помощь.Опять же, извините, если это дубликат, но я не могу решить эту проблему с другими потоками ..

1 Ответ

0 голосов
/ 17 декабря 2018

Вы запросили пример кода:

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);
}

Примечания:

  • Вы выделяете память для строки на 1 больше, чем длина, потому что строка в Cимеет нулевой завершающий символ.

  • не используйте подчеркивания перед именем идентификатора - они зарезервированы для компилятора.

  • не приводятрезультат malloc.Он возвращает указатель void, который совместим с указателем любого типа.

  • этот пример включает в себя все необходимые проверки ошибок.

...