in C (unter Verwendung von gcc) I kann eine variable Länge struct erklären, wie unten:alloc ein struct mit Null-Länge-Array mit neuen
typedef struct ProtocolFrame
{
uint8_t op;
uint32_t address;
uint16_t size;
uint8_t payload[0];
} ProtocolFrame;
dann kann ich verschiedene Rahmen Alloc:
ProtocolFrame *frA;
ProtocolFrame *frB;
frA = malloc(sizeof(ProtocolFrame) + 50);
frB = malloc(sizeof(ProtocolFrame));
In Dieses Beispiel hat ein Nutzlastfeld so groß wie 50 Bytes, und frB hat keine Nutzlast
Kann ich das gleiche in C++ mit dem neuen Operator tun?
Das ist nicht das Gleiche, denn mit malloc hat er eine dynamisch erweiterte Erweiterung, die statisch groß ist. – Puppy
Sie brauchen nicht unbedingt 'std :: malloc'. Sie könnten 'new char [sizeof (ProtocolFrame) + 50] schreiben;' aber ich weiß nicht, ob das die Ausrichtung garantiert. –
@Chris: ':: operator new (sizeof (ProtocolFrame) +50)' garantiert die Ausrichtung. –