Reputation: 83
char *format_double_trans_amount(double amount)
{
char amount_array_n[25];
strcpy(amount_array_n,"");
printf("\nInitial value ***** %s",amount_array_n);
printf("\nDouble amount ***** %f",amount);
sprintf(amount_array_n,"%1f",amount);
printf("\nFinal ........ %s", amount_array_n);
printf("\nReturn ---- %s",amount_array_n);
return amount_array_n;
}
int main()
{
printf ("\nformat_format_double_trans_amount: %s ************", format_double_trans_amount(1000.123400));
}
the result in the main method gives dump value could anybody please help me on this? output:
Initial value *
Double amount * 1000.123400
Final ........ 1000.123400
Return ---- 1000.123400
format_format_double_trans_amount: /ò# ($$Ð/Òð
Upvotes: 0
Views: 105
Reputation: 10106
You are returning a pointer to amount_array_n at end of the function format_double_trans_amount(), however the scope of that stack allocated array is limited to the body of the function. Trying to access that memory area after exiting the function will result in undefined behaviour (at best rubbish displayed and at worst a crash).
The quick and dirty fix to your program is adding static to amount_array_n:
static char amount_array_n[25];
That would make the array an effective global variable. Still, not a very elegant solution, just a quick fix for your test program.
Upvotes: 1
Reputation: 7672
amount_array_n is local variable, when you return its pointer to main function, it won't have a valid address that's why you get that output.
Upvotes: 0
Reputation: 92854
amount_array_n
being local to the function gets destroyed after the function returns. Using the returned value would invoke Undefined Behaviour.
Upvotes: 2
Reputation: 75389
When your function returns, the character array it allocated is deallocated, so when you return a pointer to that array, the pointer becomes invalid. Returning it is undefined behavior, which means the compiler can do anything. If you're really unlucky, it'll work, and you won't realize you have a problem until years later when your whole program breaks and you have no idea why. In most cases, you get garbage values or crashes.
If you want the function to return a pointer to an array, you need to dynamically allocate it, or pass in a buffer (and the buffer's size) for the function to write into.
Upvotes: 1
Reputation: 34625
You are returning the reference of a local variable which is what causing the problem.
char amount_array_n[25];
amount_arra_n
is a character array residing on stack which gets invalidated up on return of the function call.
Upvotes: 2