[英]C++: Problem with pointers in microsoft Visual Studio
I was using as my main IDE codeblocks, but I wanted to try visual studio.我用作我的主要 IDE 代码块,但我想尝试 Visual Studio。 When I run the following code in Codeblocks (or an online C++ compiler) I get the right answer (output = 61), but when I put it in visual studio I get a weird answer (output= 90).
当我在 Codeblocks(或在线 C++ 编译器)中运行以下代码时,我得到了正确的答案(输出 = 61),但是当我将它放入 Visual Studio 时,我得到了一个奇怪的答案(输出 = 90)。 Can somebody explain what is happening?
有人可以解释发生了什么吗?
#include <iostream>
int sum(int *s, int sz);
int main()
{
int arr[] = { 1,10,20,30 };
int siz = sizeof(arr) / sizeof(int);
int *ptr = arr;
int output = sum(arr, siz);
std::cout << "output = " << output << std::endl;
return 0;
}
int sum(int *int_input, int n)
{
if (n == 1)
{
return *int_input;
}
else
{
return *int_input + (sum(++int_input, --n));
}
}
Thank you for the help :)感谢您的帮助 :)
Here you have unspecified behaviour in the next line在这里,您在下一行中有未指定的行为
*int_input + (sum(++int_input, --n))
You cannot say for sure is dereferencing *int_input
is first or incrementing ++int_input
.您不能肯定地说是先取消引用
*int_input
还是增加++int_input
。 To fix it, you need to rewrite code nextly:要修复它,您接下来需要重写代码:
*int_input + (sum(int_input+1, --n))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.