数组输出具有垃圾内存值

c++ Array output has trash memory values

本文关键字:内存 输出 数组      更新时间:2023-10-16

我在c++中对数组进行练习,我得到了垃圾内存值,我该如何修复它呢?

#include<cstdlib>
#include<fsream>
#include<iostream>
#include<locale.h>
#include<string.h>
using namespace std;
string sone;
string stwo;
string sthree;
string sfour;
int one;
int two;
int three;
int four;
int main(int org, char** argv)
{
    char array = { 'a', 'b', 'c', 'd' };
    while (four <= 10)
    {
        three = 0
        while (three <= 10)
        {
            two = 0
            while (two <= 10)
            {
                one = 0
                while (one <= 10)
                {
                    setlocale(LC_CTYPE, "Local");
                    ofstream out("file.txt", ios::app);
                    sone = array[one];
                    stwo = array[two];
                    sthree = array[three];
                    sfour = array[four];
                    out << sfour + sthree + stwo + sone;
                    out << "n";
                    out.close();
                    one++;
                }
                two++;
            }
            four++;
        }
        five++;
    }
}
输出:

1-aaaa   
2-aaab   
3-aaac   
4-aaad   
5-aaa#   
6-aaa?   
7-aaa0   
8-aaa#  
9-aaa'   
10-aaa_  
11-aaa?  
12-aaba  
13-aabb  

变量one,two,three,four的取值范围是1到10。而你的数组只有4个字符。您正在访问"数组越界"

似乎你从来没有设置你的into值4等于任何东西。每次调用4++时,它都会抓取一个随机值。

另外,我不确定你是如何编译的,因为没有变量5,你正在增加它。