I have a weird problem with dynamic memory allocation.
Whenever I dynamically allocate a member of a structure with only one int
I can write us many I wanted instead of only one int
like a normal variable not an array.
This is my code with some commentary and maybe you can tell what I'm doing wrong or what point I skipped:
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int *sign_h;
int max_chars;
} myformat;
int main()
{
myformat *myfile=malloc(sizeof(myformat)); // one struct
myfile->max_chars=100;
myfile->sign_h=malloc(1*sizeof(int)); //size of one int
myfile->sign_h[333]=50; //Is this suppose to work?
printf("test %d",myfile->sign_h[333]); // printf print value of 50
FILE* f1=NULL;
char nume[]="myfile.bin";
f1=fopen(nume,"wb");
fwrite(&myfile,sizeof(myformat),1,f1);
fclose(f1);
return 0;
}
PS: And what about C++? if I make it in C++ I get different results?