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

不问归期 提交于 2019-12-02 14:01:17

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

Seems like you're quite new to C programming. Here's a thing, you simply can't use scanf to modify a value of a main function variable without using pointers. If you read about scanf, you would find out that scanf requires the memory address of a variable; that's why scanf is able to read the format string and modify your variable. So what you're trying to achieve is pretty much similar to scanf, you have to pass the address of base1; first of all declare it! Since that's what compiler is crying about. Do the following things:

  1. Declare and pass the address of the variable you want to modify. Pass the address of base1 like this:

    double base1; getBase1(); setBase1(&base1);

  2. In the function getBase1 you're doing a void return, but your function signature tells the compiler that you would return an int. So your functions should look like this:

    void getBase1(void); void setBase1(double *);

  3. Since your setBase1 is receiving an address, there is no need for an ampersand(&). Simply pass the pointer value received:

void setBase1(double *pBase) { scanf("%lf", pBase); }

You have many errors in your code, first int main(), should have the return type and your function doesn't return anything either. base1 is not declared.

error: ‘base1’ undeclared (first use in this function)
     setBase1(base1);
          ^

where is the base1 in your main function? Its basic your passing base1 as an argument to setBase1 but base1 is not declared.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!