Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does i[arr] work as well as arr[i] in C with larger data types?

It's fairly common knowledge that if you access an element of an array as arr[i] in C that you can also access the element as i[arr], because these just boil down to *(arr + i) and addition is commutative. My question is why this works for data types larger than char, because sizeof(char) is 1, and to me this should advance the pointer by just one char.

Perhaps this example makes it clearer:

#include <string.h>
#include <stdio.h>

struct large { char data[1024]; };

int main( int argc, char * argv[] )
{
    struct large arr[4];
    memset( arr, 0, sizeof( arr ) );

    printf( "%lu\n", sizeof( arr ) ); // prints 4096

    strcpy( arr[0].data, "should not be accessed (and is not)" );
    strcpy( arr[1].data, "Hello world!" );

    printf( "%s, %s, %s\n", arr[1].data, 1[arr].data, (*(arr+1)).data );
    // prints Hello world!, Hello world!, Hello world!
    // I expected `hold not be accessed (and is not)' for #3 at least

    return 0;

}

So why does adding one to the array pointer advance it by sizeof( struct large )?

like image 660
RC Howe Avatar asked Aug 24 '11 19:08

RC Howe


People also ask

What is arr I in C language?

An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc.

Is arr I Same as I arr?

arr gives base address of the array since its array name. So both are same.

Can C array have different data types?

You can't have an array of different types, exactly.

What is array explain different types of array in C language?

Array in C are of two types; Single dimensional arrays and Multidimensional arrays. Single Dimensional Arrays: Single dimensional array or 1-D array is the simplest form of arrays that can be found in C. This type of array consists of elements of similar types and these elements can be accessed through their indices.


2 Answers

That's pointer arithmetic. When you write

some_pointer + i 

it is compiled as

some_pointer + (i * sizeof(*my_pointer))

(i is an int for that matter :) )

like image 109
MByD Avatar answered Oct 30 '22 13:10

MByD


This sort of question can always be answered by reading the C spec. Try it!

§6.5.6 Additive Operators, paragraph 8:

When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression.

like image 29
Stephen Canon Avatar answered Oct 30 '22 14:10

Stephen Canon