i obtained a double value with decimal part as 0 from calculations and then want to convert this value into char array consisting of the digits as elements(using ascii codes) and then return it…i wrote the following code for it…
char* as_string(double a,char* ptr)
{
int digits=0;
for(int i=1;;i++)
{if(static_cast<int>(a/pow(10.0,i))==0)
{digits=i;
break;}
}
char b[digits];
for(int i=digits-1;i>=0;i--)
{
b[digits-1-i]=static_cast<int>(a/pow(10.0,i))+48;
a=a-((b[digits-1-i]-48)*pow(10.0,i));
}
strncpy(ptr,b,digits);
return ptr;
}
everything went on all right…there was no syntax error but at runtime the prog was aboted each time…after some scrutiny i found that error is taking place around pointer ptr and strcpy statements(as the array b was successfully tested as filled with the digits )…can anyone plz. point out the error?
You should ask yourself the Question:
Is
ptrpointing to a memory location big enough to holddigits?I don’t think so.
The problem is you are passing a pointer
ptrto the function but you don’t know before hand how much memory is needed to be allocated toptr.You can have two options:
You can guess the maximum value possible allocate the same to
ptrusingnewor on stack & then passptrto the functionOr
You allocate memory to
ptrinside the function usingnewwhere you know exactly how much memory is needed. Note that to do so you will have to passptras a double pointer.