c++ - 在尝试使用递归查找集合子集的总数时,我遇到了分段错误
问题描述
//递归程序查找集合的所有子集
#include<iostream>
using namespace std;
const int n =3;
int arr[n]={1,2,3};
void pass(int *tmp,int tmpArrayIndex, int OriginalArrayIndex)
/*
* int* tmp is temporary array to store
* int tmpArrayIndex == size of array is diiferent at different level, indicates the position to insert element
* int OriginalArrayIndex == positon of element in original array for which decision is to made ot select or reject a element
*/
{
if(OriginalArrayIndex == n)
{
cout<<tmp<<endl;
return;
}
tmp[tmpArrayIndex] = arr[OriginalArrayIndex];
pass(tmp,tmpArrayIndex+1,OriginalArrayIndex+1);
pass(tmp,tmpArrayIndex,OriginalArrayIndex+1);
}
int main(void)
{
int *tmp;
pass(tmp,0,0);
return 0;
}
程序编译成功,但在执行时显示分段错误。上述程序的预期输出应该是 123 12 13 1 23 2 empty total 8 个子集,如 2^3=8。
解决方案
"array" 没有引用或指针tmp
。该变量tmp
是一个指针 true,但如果你这样做,tmp = new int[3]
那么tmp
将指向一个新数组的第一个元素,它与arr
. 并tmp[i] = arr[i]
复制元素,这两个数组仍然是不同的和分开的,并且指向的数组中的tmp
任何内容都不会“引用”或“指向” 的任何元素arr
。
从图形上看,两个数组和指针看起来像这样(在 之后tmp = new int[3]
):
+--------+--------+--------+ | arr[0] | arr[1] | arr[2] | +--------+--------+--------+ +-----+ +--------+--------+--------+ | 温度 | --> | 时间[0] | 时间[1] | 时间[2] | +-----+ +--------+--------+--------+
这两个数组是两个独立且不同的实体,没有关系。
如前所述
tmp[i] = arr[i];
将值从 复制arr[i]
到tmp[i]
。这类似于做
int temporary_value_copy = arr[i];
tmp[i] = temporary_value_copy;
有了上面的两行,你还会声称tmp[i]
“引用”或“指向”arr[i]
吗?我希望不是。
此外(如前所述),since tmp
is a pointer then
std::cout << tmp;
将打印指针本身,而不是它可能指向的可能数据。要打印tmp
指向的数组的所有元素,您需要一个循环:
for (size_t i = 0; i < 3; ++i)
std::cout << tmp[i];
推荐阅读
- javascript - 错误:对等体被破坏后无法发出信号 - 简单对等体
- python - 使用 For 循环生成 Pandas 数据帧
- javascript - 为什么本地存储不加载
- ios - 由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'-[__NSCFBoolean length]
- python - 每次在 for 循环中创建一个新变量
- powerbi - 如果数字有“.00”,如何添加逗号千位分隔符显示错误
- c - 带有 char[] 的 C 指针,忽略 const 关键字?
- php - 目标类 [StudentController] 不存在。http://localhost:8000/学生
- javascript - 如何从 Firestore 中的字段获取数组的值(在 Javascript 中)
- python - 返回其索引在另一个数组中指定的元素数组