[Solved] Can we add an array variable to integer?


In expressions an array designator is implicitly converted to the pointer to its first element. Adding an integer to a pointer you will get again a pointer. It is so called the pointer arithmetic.

Thus for example if you have an array

int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
const size_t N = sizeof( a ) / sizeof( *a );

then expression

a + N / 2 

will point to the sixth element of the array.

Here is a demonstrative program

#include <stdio.h>

int main(void) 
{
    int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    const size_t N = sizeof( a ) / sizeof( *a );

    for ( size_t i = 0; i < N; i++ ) printf( "%p: %d\n", a + i, *( a + i ) );

    return 0;
}

Its output might look like

0xbfd3d9c8: 0
0xbfd3d9cc: 1
0xbfd3d9d0: 2
0xbfd3d9d4: 3
0xbfd3d9d8: 4
0xbfd3d9dc: 5
0xbfd3d9e0: 6
0xbfd3d9e4: 7
0xbfd3d9e8: 8
0xbfd3d9ec: 9

Also a function parameter declared like an array is also adjusted to pointer. So for example these function declarations

int median(int a[100], int n); 
int median(int a[10], int n); 
int median(int a[], int n);
int median(int *a, int n);  

are equivalent and declare the same one function.

1

solved Can we add an array variable to integer?