/* * 请编写一个函数,该函数将给定的一个整数转换为字符串 */ #include<stdio.h> #include<stdlib.h> /* * 判断value>0或value<0或value=0 */ char *convert(int value) { int a[20]; int loc=0; char *s; char *t; bool flag=true; int addition=0; if(value==0) { s=(char *)malloc(2); t=s; if(s==NULL) { printf("create fail!\n"); exit(1); } *t=0+'0'; t++; *t='\0'; return s; } //用flag来标记value是正数还是负数 else if(value<0) { value*=-1; flag=false; } else flag=true; while(value>0) { int temp=value%10; a[loc]=temp; loc++; value/=10; } //如果是负数,多申请一个空间用来存储'-' if(flag==false)addition++; s=(char *)malloc(loc+addition+1); t=s; if(s==NULL) { printf("create fail!\n"); exit(1); } if(flag==false) { *t='-'; t++; } for(int i=loc-1;i>=0;i--) { *t=*(a+i)+'0'; t++; } *t='\0'; return s; } int main() { int value=123; char *s=convert(value); printf("%s\n",s); return 0; }