+ 1

index pointer in C

The code is including element in array with overlapping. But the code I wrote has some problem, but I can't recognize the problem. Please help me. https://code.sololearn.com/c4wRoKBfy94Y/#c

28th May 2019, 1:39 PM
김도현
김도현 - avatar
1 Odpowiedź
+ 3
The for-loop in main sets i = index and since index is uninitialized it contains garbage values probably higher than the loop condition you check for, so it overruns the array buffer. You could pass just the arr as a pointer argument, the ints can be passed by value. Since you are not modifying the values of those ints in the add_to_set function there's no need for them. Anyway you probably want something like this: #include <stdio.h> #define SIZE 10 void add_to_set(int *arr, const int *index, int *ele) { int i; arr[*index]=*ele; *ele = 0; for (i = 0; i <= *index; i++) printf("%d, ", arr[i]); } int main(void) { int i; int arr[SIZE]; int ele = 0; int index = 0; for (i = 0; i < SIZE; i++) { printf(" include element in array? "); scanf("%d", &ele); index = i; add_to_set(arr, &index, &ele); putchar('\n'); } return 0; }
28th May 2019, 4:14 PM
Cluck'n'Coder
Cluck'n'Coder - avatar