Home > database >  How do I call a print function in other functions in C?
How do I call a print function in other functions in C?

Time:11-24

I have to call for one printf function for X number of different functions. I am struggling to call the printf function from the returnString function in the other two functions. I am new to C and I am used to Java so I am not sure how to fix this. This is what I have tried:

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

CodePudding user response:

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.

  • Related