如何在C void函数的指针的作品? [英] How does a void function in C works with pointers?

查看:239
本文介绍了如何在C void函数的指针的作品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建C编程与工作的指针void函数。我创建了以下功能与指针的作品:

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 \n", numerator,denominator,finalAnswer);
}

有与此程序没有问题,但是当我改变的第一行后,

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

#include <stdio.h>

这样:无效function_1为(int * NUM1,为int * NUM2){
我碰到下面的错误,当我尝试编译我的code:

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]

很抱歉,如果我做一些愚蠢的,但我不知道当我改变INT作废什么是错的。我知道虚空意味着什么,但我想我的code。与空返回。是否可以?
谢谢

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

推荐答案

您正在做的几件事情错了,显然与一些概念混淆自己。

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


  1. 函数声明为无效F()不能返回一个值。这已无关的指针。当你改变你的函数以回归无效,你不能使用返回值; 在函数内部(或更准确地说,无论你的价值回归将不会去任何地方,这就是为什么你有一个编译时警告)。

  2. 如果你定义一个变量是指针类型,则需要使用该地址前,一个有效的内存地址分配给它。 为int *总是从来没有分配任何地址,并使用它( *总= * NUM1 / * NUM2; )是危险的并创建未定义的行为。

  3. 您不需要是一个指针类型的。只要做到:

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


  • 您在不使用 function_1 的任何地方,因此,所有上面是无关紧要的: - )

  • You're not using function_1 anywhere, so all the above is irrelevant :-)
  • 这篇关于如何在C void函数的指针的作品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆