I was trying to print the location of array elements using the following code

#include<stdio.h>
main()
{
	int arr[]={10,20,30,40,50,60};
	int i;
	for (i=0; i<6; i++)
		printf("%d ", &arr[i]);
	return 0;
}

Error: printArrayLocation.c:7:3: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘int *’

While i was googling for the solution, I came across the following codes.

for (i=0; i<6; i++)
	printf("%p ", (void *) arr[i]);

Result: 0xa 0x14 0x1e 0x28 0x32 0x3c

for (i=0; i<6; i++)
	printf("%p ", arr+i);

Result: 0xbf8985a4 0xbf8985a8 0xbf8985ac 0xbf8985b0 0xbf8985b4 0xbf8985b8

Both are giving results.
I know that arr points to the element with index 0, and that arr+i will point to the subsequent elements, but what is %p?
Please also explain the 2nd code(no idea what's happening)
Also, why are the results in hexadecimal form?

Recommended Answers

All 3 Replies

%p = Pointer; address format
arr+3 = arr[3] -- just two different ways to access the 4th array element

thanks WaltP
What is the use of (void *)?
And why are the results in hexadecimal form? can we get them in decimal form too?

What is the use of (void *)?

The %p specifier expects a pointer to void (the generic pointer type in C). In cases where the address you want to print isn't already a pointer to void, a cast is used to make it so.

And why are the results in hexadecimal form? can we get them in decimal form too?

The display representation of addresses for %p is implementation-defined, you can't change it. If you really want decimal representation and don't mind breaking portability, you might use a decimal specifier and cast the pointer to a suitable type:

#include <stdio.h>

int main(void)
{
    int arr[] = {10,20,30,40,50,60};
    int i;
    
    for (i = 0; i < 6; i++)
        printf("%u\n", (unsigned)&arr[i]);
    
    return 0;
}

That's not likely to fail.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.