Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

How does a void function in C works with pointers?

I am trying to create a void function in C programming that works with pointers. I have created the following functions that works with pointers:

#include <stdio.h>
int function_1(int *num1, int *num2) {

    int *total;

    *total = *num1 / *num2;
    return *total;
}

int main(void) {

    int numerator;
    int denominator;
    int finalAnswer;

    printf("Numerator: ");
    scanf("%d", &numerator);

    printf("Denominator: ");
    scanf("%d", &denominator);

    finalAnswer = numerator / denominator;
    printf("%d / %d = %d 
", numerator,denominator,finalAnswer);
}

There is no problem with this program, but when I change the first line after

#include <stdio.h>

to this : void function_1(int *num1, int *num2) { I get the following error when I try to compile my code :

prog1.c: In function ‘function_1’:
prog1.c:7:2: warning: ‘return’ with a value, in function returning void [enabled by default]

Sorry if I am doing something silly, but I have no idea what is wrong when I change int to void. I know void means nothing, but I want my code to return with void. Is it possible? Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're doing several things wrong, and apparently confusing yourself with some concepts.

  1. A function declared as void f() can't return a value. That has nothing to do with pointers. When you change your function to "return void", you can't use return value; inside the function (or more accurately, whatever value your return will not go anywhere, which is why you have a compile-time warning).
  2. If you define a variable to be a pointer type, you need to assign a valid memory address to it before using that address. int *total is never assigned any address and using it (*total = *num1 / *num2;) is dangerous and creates undefined behavior.
  3. You don't need total to be a pointer type at all. Just do:

    int function_1(int *num1, int *num2) {
        int total;
    
        total = *num1 / *num2;
        return total;
    }
    
  4. You're not using function_1 anywhere, so all the above is irrelevant :-)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...