"Implement function int *create_dyn_array(unsigned int n) that allocates an int array for n integers. n is given as argument to the function when it is called. After allocating the array, the function should read the given number of integers to the array from user, using the scanf function. After the right amount of integers have been read, the function returns pointer to the dynamically allocated array."
I am getting a segmentation fault no matter what I do. Also, for some reason the scanf takes in 6 integers, even if I change the for loop "n" to a constant like 3 ?? Absolutely mysterious. What am I doing wrong? Thanks for any possible help here...
int *create_dyn_array(unsigned int n)
{
int *array = malloc(n * sizeof(*array));
int i;
for (i = 0; i < n; i++) {
scanf("%d\n", &(*array)[i]);
}
return *array;
}
void printarray(const int *array, int size) {
printf("{ ");
for (int i = 0; i < size; ++i) {
printf("%d, ", array[i]);
}
printf(" }\n");
}
int main()
{
int *array = create_dyn_array(5);
printarray(array, 5);
return 0;
}