The task is to create an array with different types of variables, the number of elements is not known in advance. I'm trying to help memcpy create an array with different data types, like this:

char * packet; float a=1.56; int b=5; memcpy(packet,&a,4); memcpy(packet,&b,4); 

But the segmentation fault error occurs. Tell me please, is it actually implemented in such a way, or am I trying to do something wrong?

  • 2
    You would have better voiced the task, but it is very similar that you have Error XY . - αλεχολυτ
  • 2
    "create an array with different types of variables" - and how are you going to store information about the type of each variable in such an array? Without it, it will be useless. - PinkTux
  • 2
    If you need to store absolutely any type, then look at boost::any . If there is any hierarchy of stored types, then (smart) pointers can be used. All this as a type for std::vector , for example. True, I suspect that it will be difficult for you at the moment. - αλεχολυτ
  • @infernalcucumber This phrase "The task is to create an array with different types of variables, the number of elements is not known in advance" does not make sense. Give the exact wording of what is required. And the phrase you quoted is just illiterate from a programming point of view. :) - Vlad from Moscow

2 answers 2

 char *packet; /* ... */ memcpy(packet,&a,4); 

You declared a pointer, but did not allocate the memory it points to.

Or:

 char packet[4]; // или сколько вам надо 

or:

 char *packet = new char[4]; // или сколько вам надо 

PS Do you C++ need C++ in this case?

  • Thanks, you can si of course. Option if you specify the dimension of the array immediately works. But I have a problem here that I don’t know what dimension it will have in advance, so I’m looking forward to adding as far as ... - infernalcucumber
  • one
    So, it is necessary to store the current size somewhere, and stretch if necessary. For C this is realloc (do not make a classic mistake with the loss of a pointer if realloc() returns NULL ), for C++ is new / memcpy() / delete . - PinkTux

You make a mistake, and fundamentally wrong :)

You have already indicated the error - you did not allocate memory, and you are trying to write where it is not clear.

But after you write to the allocated memory - what do you want to do with this next? Why this torment? After all, you need somewhere separately to store information like:

 Элемент 0 Смещение 0 тип double Элемент 1 Смещение 8 тип char Элемент 2 Смещение 9 тип int 

All this is good only for POD - that is, roughly speaking, the types of good old C, but not C ++. Question: in the name of what are these torments?

Formulate your most important task - perhaps it can be solved much easier ...

  • I think a person invent protobuf (or something like that) - KoVadim
  • @KoVadim Or simply a bicycle ... - Harry