开发者

how to write a function that would return a string in c

开发者 https://www.devze.com 2023-03-01 23:58 出处:网络
How to return a string from the function: char * temp; int main() { temp = malloc(129); double g_symbol_b_amount = 8536.700000;

How to return a string from the function:

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;
}

Here I got the value: 0.000000

I need the orginal value, please help me on this?


I've tested the code below and it behaves correctly. Can you please confirm.

#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);
}


Your printf() format string should have %s instead of %f because the value being passed (the value returned from format_double_trans_amount) is a char * and not a double.

I think you should also change your format_double_trans_amount() function to:

char *format_double_trans_amount(double amount)
{      
    sprintf(temp,"%1f",amount);   
    return temp;  
}
0

精彩评论

暂无评论...
验证码 换一张
取 消