0

我搜索了这个特定的错误,发现根本问题涉及循环计数错误并导致程序超出数组的界限。

但是,在我将每个数组降低到数组开始丢失输出数据的点之后,它继续抛出相同的错误。我仍然是 C/C++ 的新手,但对此的任何见解将不胜感激。

该程序似乎运行到最后,甚至返回到 main 方法。

#include <stdio.h>



void sortAr(char[]);

    int main ()
{
    char a='y';
    char b,i;
    char c[20];
    int x=0,n=0,z=0;
    while (x<=19)
    {
        c[x]='@'; 
        x++;
    }

    printf("Enter 20 letters: \n"); 

    while (z<=20) //(The '=' caused my problem, removed and it runs fine.)
    {
        z++;
        x=0;
        b='y';
        scanf("%c",&i);
        while (x<=19)
        {
            if (c[x]==i)
                b='n';
            x++;
        }

        if (b=='y')
        {
            c[n]=i;
            n++;
        }
    }
    printf("\n");
    printf("The nonduplicate values are: \n");      

    sortAr(c);

}





    void sortAr(char ar[])
    {
        char z;
    for (int i = 0; i <= 19; i++) 
    {
        for (int j=i+1; j <= 19; ++j)
        {
            if (ar[i]>ar[j])
            {
                z =  ar[i];
                ar[i] = ar[j];
                ar[j] = z;
            }
        }
    }
    for (int i = 0; i < 20; i++) 
    {
        if(ar[i]=='@')
            continue;
        printf("%c ", ar[i]);
    }
    printf("\n");
    }
4

1 回答 1

3

我在以下位置发现了错误:

while (z<=20)

原因是数组会覆盖比预期更多的字符,因为执行次数比数组在内存中索引的次数多。结果,它写入了未分配给它的内存并导致 Stack_Buffer_Overrun。

Trace Z:

Z was initialized to 0.
Array was initialized to 20.

While loop starts with Z as the counter for read-ins.
z=0 array=1 1st run,
z=1 array=2 2nd run,
z=2 array=3 3rd run,
z=3 array=4 4th run,
...
z=20 array=21 21st run. (Array cannot hold 21st character and results in Stack_Buffer_Overrun.)

解决方案:

change while(z<=20) -> while(z<20)
于 2015-04-04T10:16:54.957 回答