#include "iostream.h"
int n2s(int numIn, char** pstr, int nsize)
{
int  i=0 ,j=0;
char c;
*pstr = new char[nsize+1];
for(int t=nsize-1; t>=0; t--)
{
i = numIn%10;
c='0';
c = c + i;
*pstr[t] = c;
numIn = numIn/10;
}
*pstr[nsize]='\0';
return 1; 
}
void main()
{
char* stra=NULL;
int ret = n2s(1234,&stra,4);
cout<<stra<<endl;
}
我想做一个整数转化为字符串的函数int n2s(int numIn, char** pstr, int nsize):numIn是输入的整数,pstr既做输入也是输出,nsize代表整数的位数.我的想法是转换每一位就直接把他写到数组相应的位中而不用在倒顺序了.上面的程序只要运行到
*pstr[t] = c;处就会产生Unhandle Exception错误.错在哪儿?

解决方案 »

  1.   

    int   n2s(int   numIn,   char**   pstr,   int   nsize) 

    int     i=0   ,j=0; 
    char   c; 
    *pstr   =   new   char[nsize+1]; 
    for(int   t=nsize-1;   t>=0;   t--) 

    i   =   numIn%10; 
    c= '0'; 
    c   =   c   +   i; 
    (*pstr)[t]   =   c; 
    numIn   =   numIn/10; 

    (*pstr)[nsize]= '\0'; 
    return   1;   
      

  2.   

    *pstr[t]   =   c; 替换为*(*(pstr)+t) =  c;
    其他的类似
      

  3.   

    代码还可以改进下..hehe
    ------
    int n2s(int numIn, char **pstr, int nsize) 

    int   i=0, j=0; 
    char  c; 
    *pstr = new char[nsize+1]; 

    if (!(*pstr))
    {
    cout<<"分配内存失败.."<<endl;
    return 0;
    } for(int t = nsize-1; t >= 0; t--) 

    i = numIn % 10; 
    c= '0'; 
    c = c + i; 
    (*pstr)[t] = c ; 
    numIn = numIn / 10; 
     }  (*pstr)[nsize] = '\0'; 
    return 1;    if (*pstr)
    {
    delete *pstr;
    *pstr = NULL;
    }