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 )
?
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.
arr gives base address of the array since its array name. So both are same.
You can't have an array of different types, exactly.
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.
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 :) )
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With