First a word about terminology, your variable array
is technically not an array, it's a pointer. It can be made to point to memory that can be used as an array though.
Now for your problem: It's that when you pass arguments to functions those are passed by value, meaning they are copied. So in the function func1
the argument array
is just a copy, and changing a copy will not change the original. Since the original is not changed, you will then in the main
function dereference an uninitialized pointer, leading to undefined behavior and the crash.
To solve this you have to emulate pass by reference. This is done by passing the argument using a pointer. In this case you have to pass a pointer to the pointer.
First you of course need to change the function:
void func1(int **array) {
*array = malloc(10 * sizeof(int));
printf("Enter an int: ");
scanf("%d", &(*array)[1]);
printf("Func1: %d\n", (*array)[1]);
}
Then you need to use the address-of operator &
when calling the function
int *array;
func1(&array);
An important note: The malloc
function does not initialize the memory it allocates, which means that the contents of the memory is indeterminate. Only the second int
element of the allocated memory is initialized and can be properly referenced, reading all other elements will also lead to undefined behavior.
Another thing, that also leads to undefined behavior, and as noted by Namfuak, is that in your original function func1
you declared it as returning an integer, but you don't actually return anything. That's why I changed the function here in my answer to return void
.