Mapping a 2D C array

I have a 2d array and a pointer that points to its first element:

int s[100][100];
int* p; 

after reading some value and saving in s:

p=&s[0][0]

Well, now I want to print s-elements by accessing it through p:

for (x = 0; x<m; x++)
{
    for (y = 0; y<n; y++)
    {
        printf("%d ", *(p + sizeof(int)*x*n + y));
    }
    printf("\n");
}

where m is the number of rows and n is the number of columns. But ... It gives me the wrong answer. I think the expression "p + sizeof (int) * x * n + y" is causing the problem. Please help me fix this. Thank.

+4
source share
2 answers

You do not need arithmetic sizeof(int)- the pointer automatically processes the size of the element - change:

p + sizeof(int)*x*n + y

at

p + x*n + y
+3
source

. . , :

    printf("%d ", *(p + x*100 + y));

    printf("%d ", *(p + x*n + y));

.

+1

Source: https://habr.com/ru/post/1540137/


All Articles