How do I know the address of each vector position in C?

Asked

Viewed 3,201 times

2

I’m having trouble knowing the vector address and address of each vector position.

#include <stdio.h>

int main(){

int vec[]={52,13,12,14};

printf("Endereço de vetor %d",&vec);
printf("vec[0]%d,vec[1]%d,vec[2]%d,vec[3]%d\n", &vec[0],&vec[1],&vec[2],&vec[3]);

return 0;
}
  • If you want to display the address a pointer is referring to, use %p in place of %d.

1 answer

5


To get the vector address just use its own variable. The point is that the placeholder of formatting of printf() correct is the %p to receive a pointer. This will require a cast (void *) (generic pointer) to fit correctly (at least in compilers with safer encoding options).

The same goes for the values of the elements. But then you will use the operator & since it’s normal to take their values.

#include <stdio.h>

int main(){
    int vec[] = {52, 13, 12, 14};
    printf("Endereço de vetor %p\n", (void*)vec);
    printf("vec[0] = %p, vec[1] = %p, vec[2] = %p, vec[3] = %p\n", (void*)&vec[0], (void*)&vec[1], (void*)&vec[2], (void*)&vec[3]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • And how do I know the address of the vector in hexadecimal ?

  • 1

    It is showing in hexadecimal

Browser other questions tagged

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