C-Programming: what happens if i increment Arraypointer when passing it as an argument

Will this work? I am waiting

foo(myArraypointer + 10);

      

will be the same as

foo( &(myArraypointer[10]));

      

will this be seen as one for most compilers? Is this considered good or bad practice, and why? What could go wrong?

+3


source to share


3 answers


For any pointer or array a

and index, the i

expression a[i]

is *(a + i)

. This means that it &a[i]

is equal &*(a + i)

to where the latter can be shortened to a + i

.



+4


source


They are exactly the same as required by the C standard. Note that the compiler should not evaluate the array index before its address: i.e. The expression is well defined even if the array elements are not initialized.



I prefer the former though. It's clearer and friendlier to C ++ code, which may have overloaded the operator address for your type. And the uninitialized dot I already made is really one for the pub quiz.

+2


source


Both are the same as in the first one foo(myArraypointer + 10);

, it refers to myArraypointer

which is the base address of the variable, and +10 will increase the address to the 10th position from the base address. Increasing or decreasing the pointer address depends on the data type of the pointer Variable. those. if the pointer is a character type, it will increment / decrement by 1. If it myArraypointer

points to a character whose address is 1000, then incrementing by one will point to location 1001, but if it myArraypointer

points to an integer whose address is 1000, then incrementing by one will point to location 1002 (1000 + 2). As for float.

0


source







All Articles