Sort of related to PSET4 resize, but actually want to make sure I understand this in general.
So at first I just declared a struct BITMAPINFOHEADER called "new_bi" and dealt with it while avoiding pointers. I originally didn't alloc for the struct, just declared it. It worked, and from what I understand, it worked because it was created in the stack? Am I correct? Also what I created and dealt with is the actual struct called "new_bi".
original code example
// update outfile BITMAPINFOHEADER
BITMAPINFOHEADER new_bi;
new_bi.biSize = bi.biSize;
new_bi.biWidth = n * bi.biWidth;
new_bi.biHeight = n * bi.biHeight;
...
I tried to redo it properly, by using malloc. Since I was confused about how to implement this and figured it out through a bit of trial and error, I am writing this mainly for validation that I am understanding this correctly and didn't just get lucky and it happened to work when it shouldn't.
here is the rewritten code
// update outfile BITMAPINFOHEADER
BITMAPINFOHEADER* ptr_new_bi = malloc(sizeof(BITMAPINFOHEADER));
if(ptr_new_bi == NULL)
{
printf("Error -- out of memory\n");
return 1;
}
ptr_new_bi->biSize = bi.biSize;
ptr_new_bi->biWidth = n * bi.biWidth;
ptr_new_bi->biHeight = n * bi.biHeight;
...
So malloc returns a pointer to what you want to allocate memory for, in this case a pointer to a new struct BITMAPINFOHEADER. "ptr_new_bi" in this case, is the name of the pointer, and not the name of the actual struct like in the previous example. I am confused about how this works. Since I am only dealing with the pointer, does the actual struct remain unnamed? I never declared a struct called anything, only the pointer. So how can a struct exist without a name? If I wanted to name the actual struct and tie the pointer to it, how would I do this? can I add in:
&new_bi = ptr_new_bi;
Since &new_bi is the address of new_bi, will this name the struct "new_bi" that ptr_new_bi is pointing to. And after this can I give values to the elements in the struct like I did in the first example by just using equal sign:
new_bi.biSize = bi.biSize;
Instead of what I did in the second code, I give values to the different elements in the struct by dereferencing the pointer to the element in the struct by using "->" (instead of prefixing with a * like you would with a normal int or char.)
So along with the couple of questions I asked, I mainly just want to make sure I am understanding all this correctly. Thanks!