This has nothing to do with structures, but rather with objects being allocated on the heap or the stack.
First one: Your object is allocated on the stack, which means; when you exit the current scope (in this case the main() scope - scope means the stuff in the current {} brackets), the object will be deleted automatically, and the destructor of your struct will be called.
Second one: First thing, this will crash, because you have defined a pointer to your object, and haven't allocated space for it. The correction is the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include<stdio.h>
struct xfile{
int offset;
};
int main()
{
struct xfile *f = new xfile;
f->offset = 0x3f;
printf("0x%X\n",f->offset);
return 0;
}
|
Now f is not your object, but rather a pointer to your object for which you allocated memory with the operator "new" on the heap. When you use f->offset it's like using (*f).offset, simply. Now, you have to notice something very important, which is that when this pointer goes out of scope it will be deleted, but the OBJECT BEHIND IT WILL NOT be deleted, and will swim in your memory forever till the program closes... that's why, you're facing in this code a memory leak. And you have to correct it by deleting that object at the end of your scope.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include<stdio.h>
struct xfile{
int offset;
};
int main()
{
struct xfile *f = new xfile;
f->offset = 0x3f;
printf("0x%X\n",f->offset);
delete f;
return 0;
}
|
Hope that helps :)