如何从函数返回一个字符串:
char * temp;
int main()
{
temp = malloc(129);
double g_symbol_b_amount = 8536.700000;
printf("\n value: %s\t ", format_double_trans_amount(double g_symbol_b_amount));
}
char *format_double_trans_amount(double amount)
{
char amount_array_n1[25];
strcpy(amount_array_n, "");
sprintf(amount_array_n, "%1f", amount);
temp = amount_array_n;
return temp;
}
这里我得到的值:0.000000
我需要原始值,请帮我解决这个问题?
答案 0 :(得分:1)
您的printf()
格式字符串应该有%s
而不是%f
,因为传递的值(从format_double_trans_amount
返回的值)是char *
而不是double
。
我认为您还应该将format_double_trans_amount()
功能更改为:
char *format_double_trans_amount(double amount)
{
sprintf(temp,"%1f",amount);
return temp;
}
答案 1 :(得分:1)
我已经测试了下面的代码并且它的行为正确。你能否确认一下。
#include "stdio.h"
#include "stdlib.h"
char * temp;
char *format_double_trans_amount(double amount)
{
sprintf(temp,"%1f",amount);
return temp;
}
int main()
{
double g_symbol_b_amount = 8536.700000;
temp = (char*) malloc( sizeof(char) * 129);
printf("\n value: %s\n", format_double_trans_amount(g_symbol_b_amount));
free(temp);
}