Find the Bug in this code .
#include <stdio.h>
void initializeArray(int arr[]) {
int size = sizeof(arr) / sizeof(arr[0]); // Incorrect way to find the array size
for (int i = 0; i < size; ++i) {
arr[i] = i * i;
}
}
void printArray(int arr[]) {
int size = sizeof(arr) / sizeof(arr[0]); // Incorrect way to find the array size
for (int i = 0; i < size; ++i) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int myArray[10];
initializeArray(myArray);
printArray(myArray);
return 0;
}
1 Reply
The bug in this code is related to the incorrect way of finding the array size inside the " initializeArray " and " printArray " functions. When you pass an array to a function, it decays into a pointer, and sizeof(arr) will give you the size of the pointer, not the size of the array. 👉 To fix it you can pass the size of the array along with the array to the functions.