To dynamically allocate memory for a struct, the following can be used:
TCarro *carVariable=malloc(sizeof(TCarro)*someNumbers);
, where someNumbers
are the number of elements you want to allocate.
From the error you posted in the comment, I assume you tried doing something like:
printf("%d",carVariable);
As you have specified the integer specifier in printf (%d
), the compiler expects the function to receive an integer, but you give it a struct TCarro
instead.
So now you may be wondering, what specifier can I use to print my carVariable
?
C, actually, does not offer such specifier, because structs are types created by the programmer, so it has no idea of how to print it.
What you could do, if you wanted to print your variable would be to print each individual elements of the array.
Something like this:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct{
char nome[20];
char placaDoCarro[5];
}TCarro;
int main(void){
size_t someNumbers=10; //if you want to allocate 10 cars
TCarro *carVariable=malloc(sizeof(TCarro)*someNumbers);
//notice that struct before TCarro is not needed, as you defined it as an existing type (named TCarro)
strcpy(carVariable[0].nome,"Mercedes");
strcpy(carVariable[0].placaDoCarro,"xxxx");
strcpy(carVariable[1].nome,"Ford");
strcpy(carVariable[1].placaDoCarro,"xxxx");
//printf cars
printf("%s %s\n",carVariable[0].nome, carVariable[0].placaDoCarro);
printf("%s %s\n",carVariable[1].nome, carVariable[1].placaDoCarro);
free(carVariable);
return 0;
}
Notice that I used strcpy
, because I needed to copy a string to each field of the struct.