在增加动态数组的大小后打印动态数组



我目前正在使用动态数组在MU游戏上编写代码,并且我在打印序列时遇到了问题。

规则:如果第一个字符用字符M表示,序列的其余部分用R表示,则新序列为MRR。

的例子包括:

当前序列:MIUI

新序列:miuiui

当前序列:MUM

新序列:MUMUM

电流序列:MU

新序列:MUU

下面是我的代码片段:

在主要

:

if (userchoice == 2)
{
    if (rule2valid == false)
    {
        cout << "This rule may not be applied to your input." << endl;
        return 0;
    }       
    int newsize = size + size - 1;
    char *resultant = new char[newsize];
    resultant = applyRule2(userinput, size);
    printarray (resultant, newsize);
}   

在应用规则的函数中

char *applyRule2(char* sequence, int size)
{
int newsize = size + size - 1;
int j = 1;
char* applyRule = new char[newsize];
for (int i = 0; i < size; i++)
    applyRule[i] = sequence[i];
for (int i = size; i < newsize; i++)
{
    applyRule[i] == sequence[j];
}   
return applyRule;
}

和打印功能:

void printarray(char* sequence, int size)
{
for (int i = 0; i < size; i++){
cout << sequence[i] << "t";    
}
cout << "The length of this array is : " << size;
cout << endl;
}
问题是,当我运行程序时,我的输出是这样的:

输入:M U M

Output: M U M,该字符串的长度为5。(应该是M M M M M M)

输入:M I U I

输出:M I U I,这个字符串的长度是7。(应该是M I U I I U I)

到目前为止,我所做的是分配了一个新的动态数组,具有新的大小,并相应地向数组中添加值。但是,我不知道问题是出在applyRule2函数还是printarray函数中。

如果有人能指出正确的方向,我将不胜感激。

您的代码中有一些错误。就像阿尔夫说的,你应该用std::string。但无论如何,这里有一些错误。

for (int i = size; i < newsize; i++)
{
    applyRule[i] == sequence[j];
}
应该

for (int i = size; i < newsize; i++)
{
    applyRule[i] = sequence[j];
}

当你应该写1 = =时,你得到了一个double = ==。你的编译器应该已经警告过你了,请注意编译器的警告。

另一个错误

char *resultant = new char[newsize];
resultant = applyRule2(userinput, size);
应该

char *resultant = applyRule2(userinput, size);

您编写的代码分配了一些内存,然后在下一行它丢弃了该内存,而是使用您在applyRule2中分配的内存。所以这实际上不是一个bug,但这是对资源的浪费。您的程序将永远无法收回浪费的内存。这被称为内存泄漏

使用std::string代替原始数组和原始指针和new

最新更新