每当我尝试运行此代码时,中断都会显示或停止工作

时间:2017-02-26 18:14:28

标签: c++ arrays pointers visual-c++

我想做的是:         输入用户的句子。使用句号,空格和逗号作为单词分隔符。每个单词应存储在一个二维数组中,其列的大小不同,每行将一个单词存储为以NULL结尾的字符串。

例如,如果用户输入:

Hello how are you? 它应存储为:

H E l l o NULL

h o w NULL

a r e NULL

y o u ? NULL

因此每当我尝试运行我的代码时,都会出现此错误

Exception thrown at 0x00832605 in Project109.exe: 0xC0000005: Access violation writing location 0xFDFDFE03.   

或程序停止工作。主要问题是在 ptr[i][j] = str1[j];

`

char str1[20];
cin.get(str1, 20);

int  len, sum = 0;
len = strlen(str1);
int i = 0;

while (str1[i] != '\0')
{
    if (str1[i] == ' ' || str1[i] == '.' || str1[i] == ',' || str1[i] == '?' || str1[i] == ';')
    {
        sum = sum + 1;
    }
    i++;
}

char **ptr;
ptr = new char*[sum];
for (int i = 0; i < sum; i++)
{

    ptr[i] = new char[20];


}


for (int i = 0; i < sum; i++)
{

for (int j = 0; j < 20; j++)
{
    ptr[i][j] = '\0';
}}


for (int i = 0; i < sum; i++)
{
    for (int j = 0; j < 20; j++)
    {

        if (str1[j] == ' ' || str1[j] == '.' || str1[j] == ',' || str1[j] == '?' || str1[j] == ';')
        {
            i++;
        }

        else
        {

            ptr[i][j] = str1[j];

        }
    }
}
for (int i = 0; i < sum; i++)
{
    int j = 0;
    while (ptr[i][j] != '\0')
    {
        cout << ptr[i][j];
        j++;
    }
}


for (int i = 0; i < sum; i++)
{
    delete[] ptr[i];
}
delete[] ptr;


system("pause");
return 0;}

`

2 个答案:

答案 0 :(得分:0)

您正在使用包含0xFD的{​​{3}}索引超出范围并点击内存。

考虑这里的循环

for (int i = 0; i < sum; i++)
{
    for (int j = 0; j < 20; j++)
    {
        if (str1[j] == ' ' || str1[j] == '.' || str1[j] == ',' || str1[j] == '?' || str1[j] == ';')
        {
            i++;
        }
        else
        {
            ptr[i][j] = str1[j];
        }
    }
}

如果i已经达到(或接近)它的最大值,则在内循环中,您可能会在达到ptr[i][j] = str1[j];之前将其递增一次或多次。那时i可能超过sum

答案 1 :(得分:0)

更好的解决方案,但输出不是必需的:

{  char str1[20];
cin.get(str1, 20);

int  len, sum = 0;
len = strlen(str1);
int i = 0;

while (str1[i] != '\0')
{
    if (str1[i] == ' ' || str1[i] == '.' || str1[i] == ',' || str1[i] == '?' || str1[i] == ';')
    {
        sum = sum + 1;
    }
    i++;
}

char **ptr;
ptr = new char*[sum];
for (int i = 0; i < sum; i++)
{

    ptr[i] = new char[len];


}



for (int i = 0; i < sum; i++)
{
    for (int j = 0; j < len; j++)
    {

        if (str1[j] == ' ' || str1[j] == '.' || str1[j] == ',' || str1[j] == '?' || str1[j] == ';')
        {
            ptr[i][j] = str1[j];
            i++;
        }

        else
        {

            ptr[i][j] = str1[j];

        }
    }
}

for (int i = 0; i < sum; i++)
{
    for (int j = 0; j < len; j++)
    {
        cout << ptr[i][j];

    }
    cout << endl;
}
for (int i = 0; i < sum; i++)
{
    delete[] ptr[i];
}
delete[] ptr;


system("pause");
return 0;}