Inserting New Node

£可爱£侵袭症+ 提交于 2020-01-17 05:21:22

问题


Here is a function of a program I'm writing to get more familiar with nodes.

It creates a new node and inserts the information into the code field and then points to the existing first node. Then assigns the head to the newly created node;

Unfortunately it's giving me a incompatible types for new_node->location = code;

typedef char LibraryCode[4];

typedef struct node {
    LibraryCode location;
    struct node *next;
} Node;

void insertFirstNode(LibraryCode code, Node **listPtr) {
    Node *new_node;
    new_node=malloc(sizeof(Node));
    new_node->location = code;
    new_node->next = *listPtr;
    *listPtr = new_node;
}

回答1:


LibraryCode is typdefed as a char [4]. You can't just assign one array to another, you'll need to memcpy or strcpy the data from one array to the other.

A simpler example of what's going on:

void foo() {
   char a[4];
   char b[4];
   a = b;
}

Compiling this gives the error:

In function ‘foo’:
error: incompatible types when assigning to type ‘char[4]’ from type ‘char *’
   a = b;
     ^

You can see that you're actually trying to assign a pointer to the array, which are incompatible types.


The typedef char LibraryCode[4]; is probably not a good idea anyway. If you're going to keep a fixed-size buffer for the string in your node, then I would just ditch the typedef so it's clear what you're doing. Also, I would never pass a char [4] by value to a function. For strings, pass a const char*.



来源:https://stackoverflow.com/questions/22216607/inserting-new-node

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!