首页 > 解决方案 > 在尝试使用递归查找集合子集的总数时,我遇到了分段错误

问题描述

//递归程序查找集合的所有子集

#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。

标签: c++recursionset

解决方案


"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 tmpis a pointer then

std::cout << tmp;

将打印指针本身,而不是它可能指向的可能数据。要打印tmp指向的数组的所有元素,您需要一个循环:

for (size_t i = 0; i < 3; ++i)
    std::cout << tmp[i];

推荐阅读