阵列损坏

时间:2018-01-02 20:55:14

标签: c++ arrays

char arr[10]="\0",arr1[2][5]={'\0'};
cout<<"enter the full line : ";
gets(arr);
for (int i=0;i<1;i++)
{
    for (int j=0;j<10;j++)
    {
        if(j<=4)
        {
                arr1[0][j]=arr[j] ;
        }
        else if (j>4)
                {
                    arr1[1][j-5]=arr[j] ;
                }
        }
}

    for(int j=0;j<5;j++)
    {
        cout<<arr1[0][j]<<" ";
    }

cout<<endl;
    for(int j=0;j<5;j++)
    {
        cout<<arr1[1][j]<<" ";
    }

这里我要做的是将1d数组转换为2d数组。 我的主要目的是在2d上存储1d数组,当第一行完成时,它应该将字符串移动到它正在执行所有操作的下一行,因为我已经声明了arr [10]并通过get(arr)输入10个字符串它正在存储我想要的数组,但最后显示一个错误窗口我不知道为什么程序运行完美以及给出这个错误窗口 我的意见:hanzlaamja(10charcters)

我的输出: h a n z l a a m j a

根据我的意愿,但主要问题是错误窗口。

注意:错误框或警告框中没有任何内容。

我的程序工作正常,但我收到了数组损坏的错误。

有人可以帮帮我吗?我会非常感激 please see this error message

full picture

3 个答案:

答案 0 :(得分:3)

问题是你读了10个字符(例如“hanzlaamja”)字符串终止字符'\0',它由gets自动添加。因此,您将超出数组边界,因为这将需要11个字符的空间。所以如果你写char arr[11];就行了。但正如评论中所提到的,请不要使用gets;它不安全,它不会阻止你超出数组范围。以下代码段显示了如何更好地完成此部分:

...
char arr[11]="\0",arr1[2][5]={'\0'};
cout<<"enter the full line : ";
//    gets(arr);
if (!fgets(arr,11,stdin)) {
    cout << "no value read." << endl;
    return 1;
}
...

许多循环可以写得更短/更好阅读。但这不是实际的话题。

答案 1 :(得分:1)

除了 @Stephan Lechner 指出的重点之外,我已经尽可能地提出了一个解决方案&#34;&#34;你原来的。

2017年视觉工作室编制。

#include "stdafx.h"
#include <iostream>

using namespace std;

int main(int argc, char** argv)
{
    cout << "main - start" << endl;
    const size_t numOfRows = 2;
    const size_t numOfCol = 5;
    const size_t numCharsInSingleDimArray = 10;
    char arr[numCharsInSingleDimArray] = { '\0' }, arr1[numOfRows][numOfCol] = { '\0' };

    cout << "enter the full line : ";
    gets_s(arr);    // Note:If the buffer (arr) is too small to contain the input line and null terminator, these functions invoke an invalid parameter handle.  
    cout << "main - entered:" << arr << endl;
    char* twoDimArrStartLoc = &(arr1[0][0]);  // as user4581301  pointed out, it is also possible to "approach" it by treating the two dimensional array as a contiguous bytes in memory
    for (size_t i = 0, j = 0;  i< numCharsInSingleDimArray; ++i, ++j)
    {
        twoDimArrStartLoc[j] = arr[i];
    }

    cout << "main - after converting the 1d array into 2d array, arr1 is:" << endl;
    for (size_t i = 0; i < numOfRows; ++i)
    {
        for (size_t j = 0; j < numOfCol; ++j)
        {
            cout << "arr1[" << i << "]" << "[" << j << "]:" << arr1[i][j] << " ";
        }
        cout << endl;
    } 

    // for debug - you can remove this if not needed...
    cout << "main - end, enter any key and press enter to terminate..." << endl;
    char tmp;
    cin >> tmp;
    return 0;
}

希望它有所帮助。

干杯,

盖。

答案 2 :(得分:0)

谢谢大家的支持我正在做的MAIN错误是使用gets(arr)和做arr [10],好像你正在使用函数gets(arr)你必须给出一个额外的索引这个函数得到(arr)即arr [11] 解决了:))