请问关于atoi()函数
请教关于atoi()函数
#include <stdio.h>
char * test(void)
{
char xyz[10] = "10 ";
return xyz;
}
int main()
{
unsigned short a;
unsigned short b;
a = atoi(test());
printf( "%d\n ", a);
b = atoi( "10 ");
printf( "%d ", b);
getchar();
return 0;
}
为什么结果一个是0,一个是10呢?
谢谢
------解决方案--------------------
test函数中xyz是一个局部变量,因此他保存的内容将在test函数返回后被系统收回,而系统收回该地址后未必会立刻进行其他用途或者将之清零,因此产生了你的运行结果偶尔出现正确的情况。
但是程序中一定要避免这样的问题,因为这样返回得到的结果其值是不确定的。
------解决方案--------------------
char xyz[10] = "10 "; 定义在栈中 函数返回后自动释放
#include <stdio.h>
char * test(void)
{
char xyz[10] = "10 ";
return xyz;
}
int main()
{
unsigned short a;
unsigned short b;
a = atoi(test());
printf( "%d\n ", a);
b = atoi( "10 ");
printf( "%d ", b);
getchar();
return 0;
}
为什么结果一个是0,一个是10呢?
谢谢
------解决方案--------------------
test函数中xyz是一个局部变量,因此他保存的内容将在test函数返回后被系统收回,而系统收回该地址后未必会立刻进行其他用途或者将之清零,因此产生了你的运行结果偶尔出现正确的情况。
但是程序中一定要避免这样的问题,因为这样返回得到的结果其值是不确定的。
------解决方案--------------------
char xyz[10] = "10 "; 定义在栈中 函数返回后自动释放