为什么printf的反转的顺序()给出了不同的输出? [英] Why reverse the order of printf() gives different output?

查看:128
本文介绍了为什么printf的反转的顺序()给出了不同的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
int ∗addition(int a, int b){
    int c = a + b ;
    int ∗d = &c ;
    return d ;
}

int main (void) {
   int result = ∗(addition(1, 2));
   int ∗resultptr = addition(1, 2);

   printf("result = %d\n", ∗resultptr);
   printf("result = %d\n", result);
   return 0 ;
}

这会给出正确的答案。但奇怪的是,一旦我已经互换的最后两个printf的顺序()S,异常的回答将给予。

This will give the correct answer. But it's strange that once I have interchanged the order of the last two printf()s, abnormal answer will be given.

printf("result = %d\n", result);
printf("result = %d\n", ∗resultptr);

这是为什么?是不是因为printf的内部的一些实现()?

Why is that? Is it because some internal implementations of printf()?

我已经打开了-Wall选项,但没有警告显示。

谢谢您的解答!这是第一个问题,我的计算器。

Thank you for your answers! It's the first question for me on stackoverflow.

但为什么颠倒顺序会给出不同的答案?如果是由于返回一个局部变量,为什么第一个程序给出正确的答案,但的不确定的行为第二个不能,而唯一的区别是printf的顺序()?

But why reverse the order will give different answers? If it's due to the undefined behavior of returning an local variable, why the first program gives the correct answer but the second can't, while the only difference is the order of printf()?

推荐答案

在这个功能,

int ∗addition(int a, int b){
    int c = a + b ;   // Object on the stack
    int ∗d = &c ;     // d points to an object on the stack.
    return d ;
}

在返回指针从堆栈的对象。你从函数返回后,返回的内存是无效的。访问内存导致不确定的行为。

you are returning a pointer to an object from the stack. The returned memory is invalid after you return from the function. Accessing that memory leads to undefined behavior.

如果你改变了函数返回一个 INT ,事情会好起来的。

If you change the function to return an int, things would be OK.

int addition(int a, int b){
    return (a + b);
}

int main (void) {
   int result1 = addition(1, 2);
   int result2 = addition(2, 3);

   printf("result = %d\n", result1);
   printf("result = %d\n", result2);
   return 0 ;
}

这篇关于为什么printf的反转的顺序()给出了不同的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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