-
array of structs
Hi All
I tried to construct an array of structs, but it doesn't compile
Code:
#include <stddef.h>
#include <stdlib.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
struct Abc {
int *x ;
} *st ;
int main(void) {
st = malloc( 2 * sizeof(*st) ) ;
st[0] = (struct Abc*)malloc(sizeof(struct Abc) ) ;
st[1] = (struct Abc*)malloc(sizeof(struct Abc) ) ;
}
I guess I do something fundamentally wrong here! Any suggestions ?
thnx
LuCa
-
Try this.
Code:
#include <stddef.h>
#include <stdlib.h>
struct Abc {
int *x ;
} ;
int main(void) {
struct Abc **st = malloc( 2 * sizeof(*st) ) ;
st[0] = (struct Abc*)malloc(sizeof(**st) ) ;
st[1] = (struct Abc*)malloc(sizeof(**st) ) ;
return 0;
}
That creates an array of arrays with an Abc**.
You can also do this.
Code:
#include <stddef.h>
#include <stdlib.h>
struct Abc {
int *x ;
} ;
int main(void) {
struct Abc *st = malloc( 2 * sizeof(*st) ) ;
return 0;
}
Then st[0] is one element, and st[1] is another element. It's just that I've created an array of structures, not an array of pointers to dynamically allocated structures.
-
wow, thats fast, thanks a lot! I guess I still have to get used to pointers to pointers!