linux 如何在C语言的其他函数中调用print函数?

cdmah0mi  于 2022-11-28  发布在  Linux
关注(0)|答案(1)|浏览(139)

我必须为X个不同的函数调用一个printf函数。我正在努力从其他两个函数的returnString函数调用printf函数。我是C新手,我习惯于Java,所以我不知道如何解决这个问题。这是我所尝试的:

char returnString(double a, double b, double c, double x, double y) {
    char str[] = "time = %f, distance = %f, passengers = %f, value = %f, value = %f", a, b, c, x, y;
    printf("%s", str);
    return str[];
}

double findTime(double b, double c, double x, double y) {
    double a;
    a = 50;
    printf(returnString);
    return a;
}

double findDistance(double a, double c, double x, double y) {
    double b;
    b = 30;
    return b;
}
mwg9r5ms

mwg9r5ms1#

Allocating the string buffer in main() as a local variable and passing its address to the returnString() function would work and you do not have to be bothered by freeing the memory occupied by the OutputStr[] because the storage of local variables is freed automatically when the function ends.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

char* returnString(char* OutputStr, double a, double b, double c, double x, double y) {
    sprintf(OutputStr, "time = %f, distance = %f, passengers = %f, value = %f, value = %f", a, b, c, x, y);
    return OutputStr;
}

double findTime(double b, double c, double x, double y) {
    double a;
    a = 50;
    return a;
}

double findDistance(double a, double c, double x, double y) {
    double b;
    b = 30;
    return b;
}

int main()
{
    char OutputStr[1024];

    printf ("%s \n %f \n %f \n", returnString(OutputStr, 1.0, 2.0, 3.0, 4.0, 5.0), findTime(6.0, 7.0, 8.0, 9.0), findDistance(10.0, 11.0, 12.0, 13.0));
    return 0;
}

Of course this begs for buffer overflow if the string returned by the returnString() is longer than 1023 characters, so don't use this in a production code.
Also, allocating large variables on the stack is not a good practice, but 1024 bytes will not break anything nowadays.
In another solution it would be possible to dynamically allocate the memory for the output string ( e.g. by malloc() ) inside of the function returnString() and return the address of this memory from this function, but then you would have to remember to free this memory in main() . If you forgot then a memory leak would result, because in C there is no garbage collector to hold your hand.

  • Offtopic: In C++ you could use a smart pointer to do this automatically but C++ STL already has a string class that does it for you.*

相关问题