Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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 :-)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...