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);
};
}
In addition to ring0’s answer, the size or the amount of the arrays in your structure shouldn’t matter. You should just be aware that even if you allocate characters in your array, it doesn’t stop people from typing in longer strings (i.e., buffer overflow). You should always set a length to the scanf() formats to ensure that it doesn’t overflow. This is done by adding the
length-1in%s.Also assuming c-free 4.0 supports dynamic arrays, you need to use
malloc()to allocate your struct array following Reinderien’s advice.i.e.,