-1
我有動態內存分配的奇怪問題。 每當我動態地分配一個結構的成員只有一個int
我可以給我們寫很多我想要的而不是像普通變量那樣只有一個int
而不是數組。 這是我的一些評論代碼,也許你能告訴我在做什麼錯誤或我跳過了點什麼:C動態成員結構
#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:又是怎麼回事C++?如果我用C++編寫它,我會得到不同的結果?
恭喜你,你已經發現緩衝區溢出 –
未定義的行爲是未定義的。 – EOF
語言不會阻止你在腳下射擊自己,所以你有責任避免這樣做。 – jamesdlin