来看看下面这个函数
/*将int 变换为字符串的程序*/
char *int_to_str(int int_value){
char buf[20];
sprintf_s(buf, "%d", int_value);
return buf;
}
当我们运行这个程序的时候,会报警告。
在vs2013的编译环境中,这样并不会导致程序崩溃,只会提出一个警告。在函数buf是个局部变量,当函数运行完成,该内存区域就会被释放。那么,返回的时候,我们无法找到buf的地址。但由于现在的编译器的容错性越来越高,所以有些错误编译器是可以忽略的。
当我们将上述函数改写为如下形式
char *int_to_str(int int_value){
static char buf[20]
sprintf_s(buf, "%d", int_value);
return buf;
}
当我们将buf变量声明为static的时候,buf的内存区域一直会被静态地保持。即使函数执行结束,buf的内存区域也不会被释放。当我们return的时候,也就能找到地址了。
但是当我们改为第二形式的时候,我们两次调用int_to_str函数的时候,返回的结果都是第二次的值。因为在我们使用static变量的时候,这块内存已经被划分了,所有当我们调用这个函数多次的时候,也只是在对这块内存进行修改。所以,得到的结果永远是第二次的值。
于是我们考虑使用malloc函数。代码如下:
#include "stdio.h"
#include "malloc.h"
char *int_to_str(int int_value){
char* buf = (char *)malloc(sizeof(char)* 20);
sprintf_s(buf,20,"%d",int_value);
return buf;
}
int _tmain(int argc, _TCHAR* argv[])
{
char *s1=int_to_str(10);
char *s2 = int_to_str(20);
printf("%s,%s", s1,s2);
/*printf("%s", s1);
char *s2 = int_to_str(20);
printf("%s", s2);*/
return 0;
}
通过调试,我们发现malloc每次分配的内存是不一样。所以能够愉快的满足我们的需求。但是我并没有找到比较好的方式free掉malloc的内存。于是我只能采用下一种方式。使用数组接收参数。
#include "stdafx.h"
#include "stdio.h"
int int_to_str(int int_value,char buf[20]){
sprintf_s(buf,20,"%d",int_value);
return 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
char s1[20];
char s2[20];
int_to_str(10, s1);
int_to_str(20, s2);
printf("%s,%s", s1,s2);
/*printf("%s", s1);
char *s2 = int_to_str(20);
printf("%s", s2);*/
return 0;
}