Arrays and Pointers

Asked

Viewed 760 times

1

Hello, how do I point to a multidimensional matrix? I know that to do this with a vector (one-dimensional matrix), it’s like this:

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

I understand that very well, but with a matrix I can’t do that. When I use the same tactic for multidimensional matrix, 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? Thank you!

  • It would not be bad to include the complete code (the two-dimensional matrix statement) that actually prompted the question.

  • @epx This question is over 2 years old. At this point, this question should not even matter to the author.

  • @Victorstafusa did not notice, for some reason appeared in the list of recent questions for me...

  • @epx "Bumped by Community user".

1 answer

0

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

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

To solve your problem, simply state p adequately:

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 a 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:

  1. https://stackoverflow.com/questions/1052818/create-a-pointer-to-two-dimensional-array
  2. https://stackoverflow.com/questions/14808908/c-pointer-to-two-dimensional-array
  3. https://stackoverflow.com/questions/8617466/a-pointer-to-2d-array

Browser other questions tagged

You are not signed in. Login or sign up in order to post.