I'm having an array of struct pointers and assign real students to the array. Here's the code:
struct student {
char* firstName;
char* lastName;
int day;
int month;
int year;
};
typedef struct student* s_ptr;
int main(int argc, char **argv) {
s_ptr array = malloc(sizeof(s_ptr) * 4);
int x;
for (x = 0; x < 4; x++) {
struct student newStudent = { "john", "smith", x, x, x };
array[x] = newStudent;
}
printf("%d ", array[0].day);
printf("%d ", array[1].day);
printf("%d ", array[2].day);
printf("%d ", array[3].day);
return 0;
}
It compiles but it gives the output
0 2608 2 3
instead of
0 1 2 3
What's happening here? How to fix this?
s_ptr array = malloc(sizeof(struct student) * 4);You'll be allocation enugh space for4 students, not4 pointers!!HANDLE*to functions, whileHANDLEis actually enough. This adds needless obfuscation and makes debugging more difficult. I don't even hide function pointer typedefs behind pointers, but typedef a function type instead.