如何编写一个在c中返回字符串的函数

时间:2011-04-30 15:19:24

标签: c

如何从函数返回一个字符串:

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
我需要原始值,请帮我解决这个问题?

2 个答案:

答案 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);
}