0

As we known that the last element value of an array or an two-dimensional array can be obtained by below code:

  1. For an array:

    int a[] = {1, 2, 3, 4};
    printf("%d", *((int *)(&a + 1) - 1));
    
  2. For an two dimensional array:

    int a[2][2] = {1, 2, 3, 4};
    printf("%d", *((int *)(&a + 1) - 1));
    

Both of those code can output the correct value: 4. But when I changed the code like below:

    int foo(int a[][2]) {
        return *((int *)(&a + 1) - 1);
    }
    void main() {
        int a[2][2] = {1, 2, 3, 4};
        printf("%d", foo(a));
    }

Then I cannot get the right value. Is there anything wrong with this code? The main purpose of this code is try to get the last element value without knowing the number of elements. Is this possible? Thanks in advance.

JJ.Oloski
  • 1
  • 1

3 Answers3

0

Yes. In your first two cases, a is an array. However in the last case, a is a pointer. You are forgetting that in a function parameter, an array declarator is adjusted to a pointer declarator. Your function is actually:

int foo(int (*a)[2])
{

where a is a pointer to the first element of the array you called the function with. There is no way for the function to get the dimension of the array (or do anything that requires that information).

Related question

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365
0

When you pass an array to a function, it decays to a pointer. So when doing e.g. &a in the function, you don't get a pointer to an array of arrays of 2 integers, you get a pointer to a pointer to an array of 2 integers.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
-2

I don't know anything about C, but every language has / should have a function to check the length of array and mostly it's called length or simly count.

So, if i would want to get the last element say in php i would:

Var elmt = array[array.count-1]

I hope understood correctly what you wanted.

  • I'd humbly suggest that if you don't know anything about C, then you shouldn't answer questions about C on here – M.M Oct 19 '15 at 07:32