我必须为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;
}
1条答案
按热度按时间mwg9r5ms1#
Allocating the string buffer in
main()
as a local variable and passing its address to thereturnString()
function would work and you do not have to be bothered by freeing the memory occupied by theOutputStr[]
because the storage of local variables is freed automatically when the function ends.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 functionreturnString()
and return the address of this memory from this function, but then you would have to remember to free this memory inmain()
. If you forgot then a memory leak would result, because in C there is no garbage collector to hold your hand.string
class that does it for you.*