gpt4 book ai didi

c++ - char * 的初始化 vector 对我的电脑做了疯狂的事情

转载 作者:行者123 更新时间:2023-11-30 03:48:16 26 4
gpt4 key购买 nike

我正在尝试解决这个难题:http://www.puzzleup.com/2015/puzzle/?13

为此,我想计算所有可能的代码并将它们传递到一个 vector 中

You will produce a set of 7-letter codes using the the letters A, B, C, D, E, F and G

所以我尝试创建 char 数组的 vector 。代码分享如下:

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <cmath>

char letters[] = {'a','b','c','d','e','f','g'};

char * tempArr;
char * pastArr;


std::vector<char * > deneme;
char s1[] = {'a', 'b'};
char s2[] = {'c', 'd'};

void calculateAllPossibilities(int depth, int lastDepth)
{
//depth 1 den baþlayacak
for( int i = 0; i < sizeof(letters); i++ )
{
//

if ( depth != 1 && depth != lastDepth )
{
//
tempArr = new char[depth];
for( int j = 0; j < depth-1; j++ )
{
//
*tempArr = pastArr[j];
tempArr++;
}
*tempArr = letters[i];
for( int x = 0; x < depth; x++ )
{
//
std::cout << tempArr[x] << ",";
}
std::cout << std::endl;
delete pastArr;
pastArr = new char[depth];
for( int k = 0; k < depth; k++ )
{
//
*pastArr = tempArr[k];
pastArr++;
}
delete tempArr;
calculateAllPossibilities(depth + 1, lastDepth );
}
else if( depth == lastDepth )
{
//
tempArr = new char[depth];
for( int k = 0; k < depth - 1; k++ )
{
//
*tempArr = pastArr[k];
tempArr++;
}
*tempArr = letters[i];
for( int x = 0; x < depth; x++ )
{
//
std::cout << tempArr[x] << ",";
}
std::cout << std::endl;
deneme.push_back(tempArr);
delete tempArr;
}
else if( depth == 1 )
{
//
pastArr = new char[depth];
*pastArr = letters[i];
std::cout << pastArr[0] << std::endl;
delete tempArr;
calculateAllPossibilities(depth + 1, lastDepth );
}

}
}

int main()
{

calculateAllPossibilities(1,7);

std::cout << deneme[0][2];

return 0;
}

问题是,当我尝试在不在函数中使用 cout 的情况下计算 deneme vector 的值时,它在每次编译中都会给我不同的结果。像那些:“:”、“_”、“X”、“2”:)

但是,然后我将 cout 添加到函数中并尝试查看发生了什么,BAM!我的电脑在 cout 后变得疯狂!

我在这里做错了什么?第一次遇到这种情况。

最佳答案

这根本行不通

        deneme.push_back(tempArr);
delete tempArr;

您在 vector 中保存指向数组的指针,然后删除该数组。现在保存的指针指向任何地方。

使用 std::string 的 vector 会更好。

此外,当您使用 tempArr = new char[depth]; 分配数组时,删除时也应使用 [],如 delete[ ] 临时数组。这让编译器知道您正在删除一个数组,而不仅仅是一个字符。并不是说它在这里太重要了。

关于c++ - char * 的初始化 vector 对我的电脑做了疯狂的事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33276692/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com