Home > Software design >  How to access the individual elements of the array through array pointer?
How to access the individual elements of the array through array pointer?

Time:09-22

#include <stdio.h>
void
foo (int (*ptr)[10]) {
(*ptr[0])  ;
(*ptr[1])  ;
(*ptr[4])  ;
}

int
main(int argc, char **argv) {
int i;
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
foo(&arr);
for (i = 0; i < 10; i  ) {
    printf ("%d ", arr[i]);
}
printf ("\n");
return 0;
}

vm@ubuntu:~/src/tcpip_stack$ gcc test.c

vm@ubuntu:~/src/tcpip_stack$ ./a.out

2 2 3 4 5 6 7 8 9 10

*** stack smashing detected ***: terminated

Aborted (core dumped)

How to access the individual elements of the array through array pointer in foo ( ) ? Here it seems like, in foo() , based on array index, the entire array is being jumped as many times as index value.

CodePudding user response:

You dereference ptr incorrectly so you instead access non-existing int[10]s (out of bounds).

Corrected:

void foo(int (*ptr)[10]) {
    (*ptr)[0]  ;
    (*ptr)[1]  ;
    (*ptr)[4]  ;
}

This is in accordance with operator precedence which says that ptr[0] means the first int[10] (which is ok), ptr[1] means the second int[10] and ptr[4] means the fifth int[10], which you then dereference and try to increase the first element in. You must first dereference ptr ((*ptr)), then use the subscript operator.

Precedence Operator Description Associativity
1
[]
Post increment
Array subscripting
Left-to-right
2 * Dereference Right-to-left

This means that your code is equivalent to

void foo(int (*ptr)[10]) {
    (*(ptr[0]))  ; // increase the first element in the first (only) int[10]
    (*(ptr[1]))  ; // undefined behavior
    (*(ptr[4]))  ; // undefined behavior
}
  • Related