Matrices and Pointers

1

Hello, how do I point to a multidimensional array? I know to do this with a vector (unidmensional array), it looks like this:

int v[5];
int *ptr = v;

I understand this very well, but with an array I can not do that. When I use the same tactic for multidimensional array, this error occurs in GCC:

test.c: In function ‘main’:

test.c:5:13: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]                                                                                          
int *ptr = m;

Can you give me a light of what to do? Thanks!

    
asked by anonymous 05.11.2017 / 03:44

1 answer

0

The GCC is returning a warning saying that the int *ptr pointer is being initialized with a type that is not a ponteiro para um inteiro .

In fact, this is exactly what you are doing because v , in the case of a two-dimensional array, it is a pointer to an array of int (*p)[] integers.

To solve your problem, just declare p properly:

int v[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
int (*p)[4];
p = v;

In practice:

#include <stdio.h>

int main( void )
{
    int i = 0;
    int j = 0;

    int v[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
    int (*p)[4];
    p = v;

    for( i = 0; i < 3; i++ ) {
        for( j = 0; j < 4; j++ )
            printf("%3d", p[i][j] );
        printf("\n");
    }

    return 0;
}

The thing can be further simplified by means of typedef :

typedef int array4_t[4];
int v[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
array4_t * p = v;

In practice:

#include <stdio.h>

typedef int array4_t[4];

int main( void )
{
    int i = 0;
    int j = 0;

    int v[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
    array4_t * p = v;

    for( i = 0; i < 3; i++ ) {
        for( j = 0; j < 4; j++ )
            printf("%3d", p[i][j] );
        printf("\n");
    }

    return 0;
}

References:

  • link
  • link
  • link
  • 05.11.2017 / 13:17