联系
Knight's Tale » 技术

Be careful of the use of data format in function "scanf"

2010-06-18 23:05

when you use C-sytle scanf function, you should notice the usage of data typpe in "scanf". Everyone knows that "int" data type is an integer, its data format in "scanf" is "%d". So, you may think that "short" type is the same as "int", and you may write codes like this:

void main()
{
    const int num = 3;
    short *a = new short[num];

scanf("%d %d %d",&a[0],&a[1],&a[2]); // error!

for(int i=0;i < num;++i)
    printf("%d ",a[i]);

delete []a;

system("pause");

}

The above code is not right. The "short" type is not the same as "int" type. If you use "%d" to get "short" type data, the memory heap may be crashed because "int" type data is larger than "short" type data. You should use "hd" input data format :
void main()
{
    const int num = 3;
    short *a = new short[num];

scanf("%hd %hd %hd",&a[0],&a[1],&a[2]); // correct!

for(int i=0;i < num;++i)
    printf("%d ",a[i]);

delete []a;

system("pause");

}

Therefore, you should very be careful of "scanf" function if you are use C language. The data format should be correspond with its data type. However, if you use C++, you should use "cin" instead of "scanf".