【发布时间】:2018-08-18 13:48:02
【问题描述】:
我正在尝试实现段树。方式如下:
#include<bits/stdc++.h>
using namespace std;
int size;
int construct(int *arr,int *s,int curr,int end,int ad)
{
if(arr[curr]==arr[end])
{
s[ad]=arr[curr];
return s[ad];
}
int mid=(curr+end)/2;
s[ad]=construct(arr,s,curr,mid,ad*2+1)+construct(arr,s,mid+1,end,ad*2+2);
return s[ad];
}
int* cons(int *arr,int n)
{
int height=ceil(log2(n));
size=(int)(2*pow(2,height)-1);
int s[(int)(2*pow(2,height)-1)]={0};
construct(arr,s,0,n-1,0);
//printf("\n In cons function \n\n");
for (int i = 0; i <size; ++i)
{
printf("%d %p\n",s[i], &s[i] );
}
int *po=s;
printf("\n%p %d\n",po,size );
return po;
}
int main()
{
int arr[6]={1,3,5,7,9,11};
int *b=cons(arr,6);
printf("%p %d\n\n",b,size );
//printf("\n\n In main function \n\n");
for (int i = 0; i <size; ++i)
{
printf("%d %p\n",b[i],&b[i]);
}
return 0;
}
当我在函数 cons 中打印数组值时,它会显示预期值。然后我返回存储在主函数中的数组的起始地址。现在,当我在 main 函数中打印相同的值时,有些值是不同的,即使存储值的地址保持不变。
这是一个示例输出:
36 0x7ffce0eb6130
9 0x7ffce0eb6134
27 0x7ffce0eb6138
4 0x7ffce0eb613c
5 0x7ffce0eb6140
16 0x7ffce0eb6144
11 0x7ffce0eb6148
1 0x7ffce0eb614c
3 0x7ffce0eb6150
0 0x7ffce0eb6154
0 0x7ffce0eb6158
7 0x7ffce0eb615c
9 0x7ffce0eb6160
0 0x7ffce0eb6164
0 0x7ffce0eb6168
0x7ffce0eb6130 15
0x7ffce0eb6130 15
36 0x7ffce0eb6130
9 0x7ffce0eb6134
9 0x7ffce0eb6138
0 0x7ffce0eb613c
-521445060 0x7ffce0eb6140
32764 0x7ffce0eb6144
20 0x7ffce0eb6148
0 0x7ffce0eb614c
0 0x7ffce0eb6150
0 0x7ffce0eb6154
18 0x7ffce0eb6158
0 0x7ffce0eb615c
9 0x7ffce0eb6160
0 0x7ffce0eb6164
0 0x7ffce0eb6168
【问题讨论】:
-
我无法重现您的结果,当我运行您的代码时,两组值是相同的。我希望您的代码和您发布的结果不同步。这段代码没有产生这些结果。
-
好的做法是显式初始化
size和s。#include<bits/stdc++.h> using namespace std;也是两个不良做法的例子。这些天你也应该更喜欢nullptr而不是NULL。还;这看起来更像是用 C++ 编译器编译的 C 代码,而不是 actual 惯用的 C++ - 我建议阅读几本关于 modern C++ 的书。 -
我更新了代码,一开始我上传了错误的代码。
-
它被称为“超出范围”。使用
std::vector左右,使这东西返回一个副本。 ofc 不是指针
标签: c++ pointers c++14 dynamic-memory-allocation segment-tree