2
#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.

5
  • 1
    why not simply use void foo(int *A) and call from main: foo(a) ... Commented Sep 21, 2022 at 16:33
  • The function foo expects an array of 10 pointers ! Commented Sep 21, 2022 at 16:46
  • @YvesDaoust No, it expects a pointer to an int[10]. Neither the function signature nor the call is incorrect (although non-idiomatic). It's just the dereferencing of ptr that's wrong. Commented Sep 21, 2022 at 16:50
  • 2
    @TedLyngmo: ooops, right. After 30 years of C++, I still get stuck. Commented Sep 21, 2022 at 16:55
  • @OrenIshShalom void foo(int *A), foo(a) loses some type checking. OP's foo() expects and an array of 10 int, not any size array like foo(int *A) would accept. Commented Sep 21, 2022 at 17:43

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.