Hi, in my phase of (re)learning C, I'm often facing problems with arrays and structures (and pointers). This is a little test I wrote.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
char name[10];
} man;
int main (int argc, const char * argv[]) {
int i;
man john;
strcpy(john.name, "john");
// array of structures
man men[10];
strcpy(men[3].name, "john");
printf("*** %s ***\n", men[3].name);
// dynamic array of structures
man *men2;
men2 = malloc(10 * sizeof(man));
strcpy(men2[3].name, "john");
printf("*** %s ***\n", men2[3].name);
// multidimensional array of structures
man men3[10][10];
strcpy(men3[3][3].name, "john");
printf("*** %s ***\n", men3[3][3].name);
// dynamic multidimensional array of structures
man **men4;
men4 = malloc(10 * sizeof(man*));
for (i = 0; i < 10; i++)
men4[i] = malloc(10 * sizeof(man*));
strcpy(men4[3][3].name, "john");
printf("*** %s ***\n", men4[3][3].name);
// array of pointer to structure
man *men5[10];
men5[3] = &john;
printf("*** %s ***\n", men5[3]->name);
// dynamic array of pointers to structure
man **men6;
men6 = malloc(10 * sizeof(*men6));
men6[3] = &john;
printf("*** %s ***\n", men6[3]->name);
// dynamic multidimensional array of pointers to structures
/* ? */
return 0;
}
Can you:
- tell me if all is correct
- explain why in men4 i use
sizeof(man*)
but in men6 it issizeof(*men6)
(asterisk position) - explain how to make a dynamic multidimensional array of pointers to structures (last point)
- explain me men4? it works, but is seems to me more of an array of pointers to structure than a multidimensional array of structures!
Thanks in advance.