Hallo community,
ich bin bei meinem Projekt mal wieder auf ein Problem gestoßen, wobei ich eure Hilfe benötige. Ich möchte ein Array in einem struct mit variabler Größe haben. Es geht um folgendes Beispiel.
i have reached a point in my project where i need your help. I have a struct FAHRZEUG which contains an array of another struct, but i dont know the dimension when i create it. Here is an example
typedef struct
{
int typ;
} REIFEN;
typedef struct
{
int anzahl; // kann je nach Fahrzeugtyp zwischen 2-10 liegen
// "anzahl" can have values between 2 and 10
REIFEN test[x]; // x soll wenn möglich abhängig von "anzahl" sein
// "x" should be related to "anzahl" if possible
} FAHRZEUG;
FAHRZEUG f1;
Mein Gedanke war jetzt das ich wenn ich "x" pauschal auf den größtmöglichen Wert setze (z.B 10) ich Platz / Speicher verschwende. Richtig oder Falsch?
Will i waste memory if i set x to the highest possible number (e.g 10), although i mainly need 2,4 and 6 for x?Ich hab dann durch Tests herausgefunden, dass für "x = 2" f1.test[4].typ = 99; funktioniert, obwohl ich die Dimension von test überschreite.
I found out that this is working although it shouldn`t.
var test_array[5];
test_array[7] = 10;Mit folgender Funktion wollte ich dann genügend Speicher bereitstellen.
I have then tried to include this function to allocate enough memory.
typedef struct
{
int typ;
} REIFEN;
typedef struct
{
int anzahl;
REIFEN test[0];
} FAHRZEUG;
FAHRZEUG f1;
function setup_reifen(FAHRZEUG* f)
{
&f.test = sys_malloc(sizeof(REIFEN)*f.anzahl);
}
f1.anzahl = 4;
setup_reifen(f1);
f1.test[3] = 5;
Auch das läuftn ohne Fehler. Ich möchte nur gerne Wissen, ob der Ansatz überhaupt korrekt ist, oder ob ich mir unbewusst so den ganzen Speicher schrotte.
Im still getting no error but i don`t know if this is even correct. Will this corrupt my memory?Ich hoffe das ich mein Anliegen einigermaßen erkären konnte und bin für jede Hilfe dankbar.
I hope you can understand my question. I`m thankful for any help and sorry for my bad english.MFG