Raul Grigorașcu
Raul Grigorașcu

Reputation: 71

C pointer to last element of array

Lets say we have an array

int a[4];

there was a neat trick using pointer arithmetics to find the last element. As far as i can recall it was using the address of 'a' and incrementing it so that it will go point immediately after the array and then going one position back. The thought behind the incrementing was that that there was an implicit sizeof being done. There was nowhere any explicit sizeof.

Anyone have any idea how it was done?

Thanks a bunch!

Upvotes: 3

Views: 23226

Answers (2)

M.M
M.M

Reputation: 141628

You're probably thinking of something that involved &a + 1, which is a pointer to the memory just past the end of the struct.

However, (&a)[1][-1], or the identical expression but substituting pointer notation for array notation, *(&a + 1))[-1] or *(*(&a + 1) - 1), is technically undefined behaviour. But someone might have written this as a "clever trick" not realizing it was undefined.

((int *)(&a + 1))[-1] is well-defined and does the job, although arguably harder to read than just writing straightforward code.

Upvotes: 5

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

I can suggest the following solution

#include <stdio.h>

int main( void )
{
    int a[4] = { 0, 1, 2, 3, };

    int *p = (int *)(&a + 1) - 1;

    printf("*p = %d\n", *p);

    return 0;
}

The program output is

*p = 3

Upvotes: 10

Related Questions