Before I start I should say this is not related to a direct problem, but out of curiosity and my inability to find something relating to exactly what I'm after. I'm currently teaching myself C, I have experience with several other languages so it's nothing new other than exactly how to perform certain things.
I wanted to do a challenge in C, like build a Stack that would grow as necessary by a certain amount and I chose to use a struct for this:
#define INITIAL_STACK_SIZE 10 typedef struct Stack { int max_size; int cur_top; int *elements; } Stack; I left the elements as an empty point so it could be expanded as necessary, this made the function that build the stack like:
Stack *Stack_make() { Stack *stack = malloc(sizeof(Stack)); // This is ultimately where I become confused stack->max_size = INITIAL_STACK_SIZE; stack->cur_top = -1; stack->elements = malloc(sizeof(int) * INITIAL_STACK_SIZE); return stack; } My confusion, as I pointed out, is with the malloc for the struct. I know C aligns struct data elements in memory, so I was curious how it would do this if the elements pointer was allocated later, or secondary, to the struct itself. Is this bad practice? Is there a better approach to this?
For completeness, this is what I to expand the stack:
// Relevant bits only int new_size = stack->max_size + INITIAL_STACK_SIZE; int *elements = malloc(sizeof(int) * new_size)); if (elements != NULL) { memcpy(elements, stack->elements, sizeof(int) * stack->max_size); free(stack->elements); stack->elements = elements; } I know this isn't the best place for "code review" but if you have suggestions to improvements and what not that would be appreciated. The actual question: Is there a better way to do this in C, are there any pitfalls I'm glossing over?
sizeof(Stack)would take care of any padding added in the structure by compiler.