Address of Array in C

Shervan360 1,481 Reputation points
2020-09-05T22:25:47.877+00:00

Hello,

Could you please explain the second printf_s?
I expect &arr+1 to be similar to arr+1. because arr and &arr are the same.
Why sixteen added?

Thanks

# include <stdio.h>  
    int main()  
{  
	int arr[] = {12,14,15,23,45};  
  
	printf_s("%u %u\n",arr,&arr);  
	printf_s("%u %u", arr+1, &arr+1);   
     
	return 0;  
}  
  

22861-annotation-2020-09-05-182322.jpg

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,584 questions
0 comments No comments
{count} votes

Accepted answer
  1. RLWA32 41,811 Reputation points
    2020-09-06T00:48:08.133+00:00

    First, recognize that you are passing addresses instead of integer values to printf_s. Take a look at the warning messages issued by the compiler. In particular, note the types of the arguments that the compiler is warning about. To determine the addresses passed to the function, the compiler is doing address arithmetic based on the type of the address. In calculating the address of &arr+1 the compiler starts by taking the address of the array. The compiler looks at the type of the argument and determines that size of the int (*)[5] type is 20. So it adds 20 to the starting address of the array.

    Look at the difference in the warning messages and the result of using the following -

     printf_s("%u %u\n", arr + 1, (int*) &arr + 1);
    
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Barry Schwarz 2,271 Reputation points
    2020-09-06T02:05:18.157+00:00

    Your assumption that arr and &arr are the same is incorrect. While they happen to point to the same location in memory, they have completely different types.

    In most contexts, an expression with type array of T is automatically converted to pointer to first array element. So the expression arr is treated as if you had coded &arr[0].

    An exception to this conversion is when the expression is the operand of the & operator. In this case, no conversion is performed.

    Pointer arithmetic is always performed with an implicit scaling based on the size of the object type pointed to. On your system, an int is 4 bytes. So arr+1 points to a location just past the end of arr[0] which is four bytes away. &arr+1 points to a location just past the end of arr which is 20 bytes away.

    Also note that for the call to printf to be well defined, you should cast the values to void* and use %p as the format. While it often will work as you coded it, you should use the correct method to avoid problems when it doesn't,

    1 person found this answer helpful.
    0 comments No comments