Search code examples
cprintfscanfgetter-setter

How to use a function containing scanf() in the main function in C


The title describes what I'm trying to do, but I'm getting the error message that I never declared base1. I actually know this, but I'm not exactly sure how to actually fix the problem.

int getBase1(void);
int setBase1(double);

int main(void){
    getBase1();
    setBase1(base1);
}

int getBase1(void){
    printf("Please enter the length of a base: ");
    return;
}

int setBase1(double base1){
    scanf("%lf", &base1);
}

Solution

  • You must use pointer, otherwise the variable inside the method will not point to the same memory adress. Using pointer you'll be putting the value inside the memory address of the variable that you pass in the function call. One more thing, this way you will not need return values.

    Try this way:

    #include <stdio.h>
    void getBase1(void);
    void setBase1(double *base1);
    
    int main(void){
        double base1;
        getBase1();
        setBase1(&base1);
        printf("%lf", base1);
    }
    
    void getBase1(void){
        printf("Please enter the length of a base: ");
    }
    
    void setBase1(double *base1){
        scanf("%lf", base1);
    }