mercredi 7 avril 2021

How to deal with char array which '\0' is inserted into?

When I try to copy a struct into a char array buffer using memcpy function, '\0' is inserted into the char array. I pass the buffer pointer to a function. the content before the first '\0' is past, but the rest is lost. How can I solve this problem? I would appreciate it if you help me.

here is the code, although the the struct Mystruct and the function display() is not designed reasonably。

#include <QCoreApplication>

#include <stdio.h>

struct MyStruct
{
    char c;
    int order;
    char ch;
    MyStruct(char c = 'b', int order = 0, char ch = 'a'):order(order), ch(ch), c(c)
    {};
};

void display(char* str)
{
    printf("%s", str);
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    MyStruct *mystruct = new MyStruct;
//    char* test = new char[50];
    char test[50];
    memset(test, 0, 50);

    memcpy(test, mystruct, sizeof(MyStruct));

    display(test);


    return a.exec();
}

I want to send struct like 'Mystruct' through socket and the function send(char*) requires a char* pointer pointing to a buffer. The '\0' is inserted into the char array when the int order is copied into the test[50].

I simplized my question with the code showed and apologize for my confusing expression.And any good way to send the struct through socket?

Aucun commentaire:

Enregistrer un commentaire