0
#include<stdio.h>

int Call();
int i,j;

int main(){
    int arr1[3][3];
    int size1 = 3,size2 = 3;
    printf("Enter the values for 6*3 matrix :");
    for (i = 0; i < size1; i++)
    {
        for(j=0;j<size2;j++)
            scanf("%d",&arr1[i][j]);
    }
    printf("\nvalues has stored\n");
    Call(size1,size2,arr1);
}

int Call(int size1,int size2,int *p){
    for (i = 0; i < size1; i++)
    {
        for ( j = 0; j < size2; j++)
        {
            printf("%d\t",*(p+i*size2+j));    
        }
        printf("\n");
    }
}

This is my first ever question asking on Stackoverflow, it may be an awkward accent and I wrote some examples below:

I know the way of reading a 2 Dimensional array by using indexes But here I tried to access the value of array with pointers.

The block of calculation got from somewhere (p+i*size2+j), it works well still, but I don't get the idea how is the process done above.

Eg: p of address => 0xffe5678 after the second execution of nested loop the value of i and j should be 0 and 1:

0xffe5678 + 0 * 3 +1 => `0xffe5679`

The result of manual calculation might be wrong however, the output prints the right value with adding the 4 bytes to the address.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • 1
    Since you have an `int*` a +1 means that the compiler knows that it has to increment the address by `sizeof(int)` to get to the next `int` object. It doesn't just add a 1 to the address – UnholySheep Feb 05 '23 at 19:12
  • Mohamed Yasar, Tip avoid using a code example where `size1 == size2`.. Use different values. It is easier to see problems when they differ. – chux - Reinstate Monica Feb 05 '23 at 19:19
  • Pointer arithmetic works the same way as array indexing, where you move to the next element by adding `1` to the index, *not* the size of the type. So `p[1]` is the same as `*(p+1)`.Note that addresses are not hexadecimal. They are addresses, which can be represented in any number base you like, so address hex `0x10` is the same address as decimal `16`. – Weather Vane Feb 05 '23 at 20:00

0 Answers0