문제

This is the code

int x, y, n, i, j, l, m, o;
printf ("podaj szerokosc planszy na jakiej chcesz zagrac\n");
scanf ("%d", &x);
printf ("podaj dlugosc planszy na jakiej chcesz zagrac\n");
scanf ("%d", &y);
int plansza [x][y];
memset(plansza, 0, sizeof plansza);
int plansza2 [x][y];
memset(plansza2, 0, sizeof plansza2);

printf("plansza: \n");
for(j=0;j<x;j++)
{
    for(l=0;l<y;l++)
    {
        printf("%d",plansza[x][y]);
        printf(" ");
    }
    printf("\n");
}

printf("plansza2: \n");
for(m=0;m<x;m++)
{
    for(o=0;o<y;o++)
    {
        printf("%d",plansza2[x][y]);
        printf(" ");
    }
    printf("\n");
}

And this is the result:
Result

Don't know why memset() doesn't work at all and I completaly dont know why. What should I do to fill the array all with zeroes?

도움이 되었습니까?

해결책

You're using x and y as indexes within your print loops despite the fact that they're not the variables actually controlling those loops.

In the first print loop, you use j and l as the control variables, and m and o in the second print loop. You need to index the array with whatever control variables you're using rather than x and y, which are the dimensions.

Let's say you entered 5 and 7 for the dimensions. This gives you elements from arr[0][0] through to arr[4][6] inclusive. Because you are using the dimensions to access the elements within the print loops, you will always get arr[5][7] which is actually outside the bounds of the array. Thats likely to just give you a value well beyond the end of the array (and the same value due to the unchanging indexes), though technically, it's undefined behaviour so it could do anything.

Once you start using the correct indexes I think you'll find memset works just fine.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top