Flying disk
Flying disk

Reputation: 130

i m unable to know the use of (int *)

I'm unable to know why do we have to use typecasting (int *) in case of 2d array? another thing I want to know is that why can't we use *(*(p+i)+j)) to access the 2d array in following code? Is it always necessary to use p + col*i + j? Why can't I use *(*(p+i)+j)) when p contains base address of array and *(*(p+i)+j)) is equivalent to a[i][j]?

Thank you in advance.

main()
{
    int a[3][4] = {
        1,2,3,4,
        5,6,7,8,
        9,0,1,6
    };

    int *p,i,j;
    p=(int *)a;       // this is my doubt why did we use int *
    for(i=0;i<3;i++)
    {
        for(j=0;j<4;j++) {
            printf("%d",*(*(p+i)+j));   // here is my 2nd doubt
        }
    }
}

Upvotes: 0

Views: 141

Answers (2)

SzG
SzG

Reputation: 12619

Your code does not even compile, exactly where your 2nd place of doubt is. I've corrected it:

#include <stdio.h>                                                  
int main(int argc, char *argv[])                                    
{                                                                   
    int a[3][4] = {                                                 
        1,2,3,4,
        5,6,7,8,                                                  
        9,0,1,6,
    };                                                              

    int *p, i, j;                                                   
    p = a[0];       // No cast, just address the 1st row
    for (i = 0; i < 3; i++) {                                       
        for (j = 0; j < 4; j++) {                                   
            printf("%d", *(p + 4*i + j));   // corrected pointer arithmetic
        }                                                           
    }                                                               
}                                                                   

Pointer p does not know it's addressing a 2-dim array, it's just an int pointer. Are you sure you want to print the numbers without even separating them by whitespace?

Upvotes: 1

igon
igon

Reputation: 3046

The code you provided does not compile because of line:

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

where you are dereferencing twice an int*

You can create a pointer to reference the array a of type pointer to array of 4 elements. See the attached code where are all pointers are printed out during the execution of the nested for loop.

#include<stdio.h>

main()
{
    int a[3][4]={
        1,2,3,4,
        5,6,7,8,
        9,0,1,6
    };

    int (*p)[4],i,j;
    p = a;
    for(i=0;i<3;i++){
        printf("row pointer: %p\n",p+i);
        for(j=0;j<4;j++){
            printf("element pointer: %p\n", (*(p+i))+j );
            printf("element: %d\n",*( (*(p+i)) + j ) );
        }
    }
}

Upvotes: 1

Related Questions