I have the following function (in C)
void initArr (int ** arr, int size, int value) {
* arr = (int*)malloc(size * sizeof(int));
if (*arr!=NULL) {
for (int i = 0; i<size;i++) {
*(*arr + i) = value;
}
}
}
which I call in main:
int main(void) {
int *myArr = NULL;
initArr(&myArr,10,45);
for (int i = 0; i<15; i++) {
printf("myArr[%d] = %d\n", i, *myArr);
}
return 0;
}
and the output is:
myArr[0] = 45
myArr[1] = 45
myArr[2] = 45
myArr[3] = 45
myArr[4] = 45
myArr[5] = 45
myArr[6] = 45
myArr[7] = 45
myArr[8] = 45
myArr[9] = 45
myArr[10] = 45
myArr[11] = 45
myArr[12] = 45
myArr[13] = 45
myArr[14] = 45
What I don't understand is that I've explicitly assigned only the first 10 elements of the array to the given value. However when I print past the 10th element, I see that the value is also assigned to those. Why is that?