Variable length arrays are not allowed. But then, I recently learned that user-defined function manipulates the original array, not its own personal copy. So I thought of creating a function that gets the desired size of the array by the user and therefore modifying the size (I also initialized the array in this function).
void fill_array(int array[], int size, int in_val);
void main(){
int n, value, list[1], ctr;
clrscr();
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter the value that you want all of the elements to take initially: ");
scanf("%d", &value);
printf("\nAfter scanning value, n = %d\n", n);
fill_array(list, n, value);
printf("\nAfter Function fill_array Execution");
printf("\nThe values of each element of the array is now: %d ", list[0]);
printf("%d ", list [1]);
printf("%d ", list [2]);
printf("\nn = %d\n", n);
printf("value = %d\n", value);
getch();
}
void fill_array(int array[], int size, int in_val){
int ctr;
for (ctr = 0; ctr < size; ++ctr)
array[ctr] = in_val;
printf("\nInside Function");
printf("\nn = %d\n", size);
printf("value = %d\n", in_val);
}
Here's the console / a sample run:
Enter the size of the array: 3
Enter the value that you want all of the elements to take initially: 444
After scanning value, n = 3
Inside Function
n = 3
value = 444
After Function fill_array
Execution
The value of each element of the array is now: 444 444 444
n = 444
value = 444
The function did modify list
. However, as you can see, it also changed the value of n
. After every fill_array
execution, n
always equals value
. Will someone please explain to me why the function is changing the value of n
. I don't want the value of n
to change.