I did not expect to be able to increment a pointer to a struct in a memory block of structs. But it seems to work. Is there any case where this does not work? If I create a “list” of structs then I should always be able to increment the pointer to them and C will figure out how many bytes to move by?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct User {
int id;
char name[32];
float net_worth;
};
typedef struct User User;
int main(int argc, char** argv) {
User* u1 = (User*)malloc(sizeof(User));
u1->id = 1;
strcpy(u1->name, "Mike");
u1->net_worth = 43.45;
User* u2 = (User*)malloc(sizeof(User));
u2->id = 2;
strcpy(u2->name, "Pablo");
u2->net_worth = -2.00;
User* u3 = (User*)malloc(sizeof(User));
u3->id = 3;
strcpy(u3->name, "Frederick");
u3->net_worth = 7329213.45;
User** users = (User**)malloc(sizeof(User)*10);
*users = u1;
printf("%s\n", ((User*)(*users))->name);
*users++;
*users = u2;
printf("%s\n", ((User*)(*users))->name);
*users++;
*users = u3;
printf("%s\n", ((User*)(*users))->name);
return 0;
}
This is very much by design. Assume you have
You could either access the second user via
userArray[1], or*(userArray + 1), or get a pointer to the first element and increment it via++.