I have a struct with many char array like this (and it works) :
struct maytinh {
char tenmay[10];
char mamay[10];
char test[10];
float manhinh;
int gia;
};
But if its like this,
struct maytinh {
char tenmay[99];
char mamay[99];
char test[99];
float manhinh;
int gia;
};
it breaks when I compile and scanf data in. Moreover when I put another array in the struct, it also breaks:
struct maytinh {
char tenmay[10];
char mamay[10];
char test[10];
char test2[10];
float manhinh;
int gia;
};
Why? (I'm compiling with c-free 4.0)
Here is the scanf code :
void main() {
int n,i;
printf("input :");
scanf("%d",&n);
struct maytinh a[n];
for (i=1;i<=n;i++) {
printf("May tinh so: %d\n",i);
printf("Nhap ten may :");
scanf("%s",a[i].tenmay);
printf("Nhap ma may :");
scanf("%s",a[i].mamay);
printf("Nhap test :");
scanf("%s",a[i].test);
printf("Nhap kich thuoc man hinh:");
scanf("%d",&a[i].gia);
};
}
this code totally work with the first struct. here is my fix for dynamic size struct array with malloc() and typedef (just for someone like me in need):
typedef struct maytinh {
char tenmay[99];
char mamay[99];
char test[99];
char test3[99];
float manhinh;
int gia;
};
void main(){
int n,i;
printf("input :");
scanf("%d",&n);
maytinh *a;
a=(maytinh*)malloc(n*sizeof(maytinh));
for (i=0;i<=n;i++) {
printf("May tinh so: %d\n",i);
printf("Nhap ten may :");
scanf("%s",a[i].tenmay);
printf("Nhap ma may :");
scanf("%s",a[i].mamay);
printf("Nhap test :");
scanf("%s",a[i].test);
printf("Nhap kich thuoc man hinh:");
scanf("%d",&a[i].gia);
};
}