3

I want to build a struct and contains int and char variables. Here is my code:

typedef struct {
        uint16_t type;      
        uint16_t sn;
        int data1;
        int data2;
        char crc[1024];
    }packet_t;

Then I use a method to create a struct:

packet_t packetCreate(uint16_t type,uint16_t sn, uint16_t data1, 
uint16_t data2, char crc[1024])
{
    packet_t packet;
    packet.type = type;
    packet.sn = sn; 
    packet.data1 = data1;
    packet.data2 = data2;
    packet.crc = crcr;
    return packet;
}

Also I have defined the corresponding variables in the code. But when I compile the code it doesn't work and displays:

incompatible types when assigning to type ‘char[1024]’ from type ‘char *’ in the line: packet.crc = crcr; How should I define and use the struct? I want to build the struct contains a char string, so I can store the CRC strings of data.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
zhonghao
  • 79
  • 5

4 Answers4

3

Use memcpy. i.e.

memcpy(packet.crc, crc, sizeof(packet.crc));

To copy the contents into the array.

You need

#include <string.h>

to use this function

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
  • NB missing comma - should be `memcpy(packet.crc, crc, sizeof(packet.crc));` - I can't try to edit this in because I need to put at least 6 characters in for that – tom Apr 23 '16 at 16:05
3

You cant just assign string to another string.Like

packet.crc = crc;

The above method is wrong. You need to use command strcpy here from library string.

strcpy(packet.crc,crc);

Don't forget to call library string.h.

Pavan
  • 250
  • 3
  • 13
2

You can not directly assign arrays to each other. You may use library functions like memcpy(), (or strcpy() in the case of a null terminated string). Another way is to copy the elements from the source array to the destination one by one by a loop.

Yağmur Oymak
  • 467
  • 4
  • 13
2

In addition to the other comments I am concerned that you define your packet_t variable packet inside the function and when the function returns the memory allocated to packet will 'disappear'.

It is better to declare packet in main and then call the routine with the address of packet - or the pointer to packet.

You can then change your function to

void packetCreate(packet_t *p_packet, ruint16_t type,uint16_t sn, uint16_t data1, 
uint16_t data2, char crc[1024])
{
   // p_packetn =  &packet - it is a pointer to the packet
    p_packet->type = type;
    p_packet->sn = sn; 
    p_packet->data1 = data1;
    p_packet->data2 = data2;
    p_packet->crc = crcr; // note other answers to correct this line
    return ;
}
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
tom
  • 1,303
  • 10
  • 17