Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different Pointer Arithmetic Results when Taking Address of Array

Program:

#include<stdio.h>  int main(void) {     int x[4];     printf("%p\n", x);     printf("%p\n", x + 1);     printf("%p\n", &x);     printf("%p\n", &x + 1); } 

Output:

$ ./a.out 0xbff93510 0xbff93514 0xbff93510 0xbff93520 $ 

I expect that the following is the output of the above program. For example:

x        // 0x100 x+1      // 0x104  Because x is an integer array &x       // 0x100  Address of array &x+1     // 0x104 

But the output of the last statement is different from whast I expected. &x is also the address of the array. So incrementing 1 on this will print the address incremented by 4. But &x+1 gives the address incremented by 10. Why?

like image 965
mohangraj Avatar asked Nov 18 '15 09:11

mohangraj


People also ask

How is pointer arithmetic different?

When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size of an int) and the new address it will points to 1002.

How many different operations we can perform using pointer arithmetic?

You can perform a limited number of arithmetic operations on pointers. These operations are: Increment and decrement. Addition and subtraction.

What is the relationship between array notation and pointer arithmetic?

An array is represented by a variable that is associated with the address of its first storage location. A pointer is also the address of a storage location with a defined type, so D permits the use of the array [ ] index notation with both pointer variables and array variables.

What is difference between pointer to array and array of pointers?

A user creates a pointer for storing the address of any given array. A user creates an array of pointers that basically acts as an array of multiple pointer variables. It is alternatively known as an array pointer. These are alternatively known as pointer arrays.


1 Answers

x -> Points to the first element of the array. &x ->Points to the entire array. 

Stumbled upon a descriptive explanation here: http://arjunsreedharan.org/post/69303442896/the-difference-between-arr-and-arr-how-to-find

SO link: Why is arr and &arr the same?

like image 71
thepace Avatar answered Sep 23 '22 02:09

thepace