CzadowyHuopak
CzadowyHuopak

Reputation: 35

How to move in the 2d/3d array using pointers in C?

Today I was coding a little bit for my studies. And I have a problem with 2d (and also 3d arrays in C). When I allocate memory for an array or make a static array for example:

//dynamic
int *a=(int *)malloc(5*5*sizeof(int));
     //OR 
//static
int ar[5][5] = {0};
int *a= ar[0][0];

I don't know how to properly move in this matrix using pointers. I tried a for loop looking like this to print its elements:

for(int i=0;i<5;i++){
   for(int j=0;j<5;j++){
     printf("%d ",*((a+i)+j));
   }
   puts("\n");
 }

But it doesn't work. When i inputed to the array first 25 int numbers starting with 1,like this:

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

I got printf output like:

1 6 11 16 21
6 11 16 21 22
11 16 21 22 23
16 21 22 23 24
21 22 23 24 25

The output includes only first column and last row.

I saw a tutorial on youtube how to properly do this, but somehow i missunderstood this topic. Can somebody show me how to do this using pointers, please?

Thanks for your time!

Upvotes: 0

Views: 366

Answers (1)

Barmar
Barmar

Reputation: 781210

You need to multiply the row index by the row length to get to that row.

 printf("%d ",*((a+i*5)+j));

Upvotes: 4

Related Questions