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.

3

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Note: C does not have a string type. It is all convention. And they are not the same types anyway. The member is an array, the paramter is a pointer.
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

1 Comment

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.