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

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

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

  1. char returnString(double a, double b, double c, double x, double y) {
  2. char str[] = "time = %f, distance = %f, passengers = %f, value = %f, value = %f", a, b, c, x, y;
  3. printf("%s", str);
  4. return str[];
  5. }
  6. double findTime(double b, double c, double x, double y) {
  7. double a;
  8. a = 50;
  9. printf(returnString);
  10. return a;
  11. }
  12. double findDistance(double a, double c, double x, double y) {
  13. double b;
  14. b = 30;
  15. return b;
  16. }
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.

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdio.h>
  3. char* returnString(char* OutputStr, double a, double b, double c, double x, double y) {
  4. sprintf(OutputStr, "time = %f, distance = %f, passengers = %f, value = %f, value = %f", a, b, c, x, y);
  5. return OutputStr;
  6. }
  7. double findTime(double b, double c, double x, double y) {
  8. double a;
  9. a = 50;
  10. return a;
  11. }
  12. double findDistance(double a, double c, double x, double y) {
  13. double b;
  14. b = 30;
  15. return b;
  16. }
  17. int main()
  18. {
  19. char OutputStr[1024];
  20. 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));
  21. return 0;
  22. }

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.*
展开查看全部

相关问题