Doubt about pointer and matrix

Asked

Viewed 55 times

2

Hello, I was trying to do an exercise in which you asked to print the address of each position of the matrix using pointer and I am in doubt if it is correct. I searched some videos on youtube and only found explanation for one-dimensional matrices.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    float matrix[3][3];
    float **xmatrix= matrix;

    printf("Endereços de memória\n\n");

    for(int i=0; i<3; i++)
    {
        for(int j=0; j<3; j++)
        {

            printf("Membro [%d] [%d]\n\n",i,j);
            printf("%d\n\n\n",xmatrix+j+i);\\aqui fiquei em dúvida em com faria para imprimir os próximos 
                                           \\membros

        }
    }

    return 0;
}

inserir a descrição da imagem aqui

And if I’m right ,because some of the addresses are repeated.

Thanks in advance.

  • 1

    it is repeating because you are adding the address + i + j, note for example in the cases [0][1] and [1][0] are equal pq x+1+0 = x+0+1 , in my view the easiest way to get the pointer addresses would be with a & in Matrix, ex: &Matrix[0][1]

  • 1

    If you want to use the way it is in your program the correct formula is: xmatrix+j+(2*i) where this 2 is the row size of your matrix.

1 answer

2

In C, the best way to display the address of a pointer is by using the conversion specifier %p in the format string of printf().

To get the address of a variable use the operator &, see just how your program would look:

#include <stdio.h>

int main(void)
{
    int i, j;
    float matrix[3][3];

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

    return 0;
}

Possible exit:

0,0 = 0x7ffd005baad0
0,1 = 0x7ffd005baad4
0,2 = 0x7ffd005baad8
1,0 = 0x7ffd005baadc
1,1 = 0x7ffd005baae0
1,2 = 0x7ffd005baae4
2,0 = 0x7ffd005baae8
2,1 = 0x7ffd005baaec
2,2 = 0x7ffd005baaf0

Browser other questions tagged

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