Correctly passing an array from a function

I have some code to generate an array of size [user_input] in a function called array_generator, using size of array from scanf in main(), and then filling it with the numbers 0 to user_input (0, 1, 2, 3, if user input is 4). The array fills correctly as printf prints

`The array contains the value 1`
`The array contains the value 2`
`The array contains the value 3`, etc.

However when I pass the array to main and printf the array values I get equal statements filled with garbage numbers. I’m also 90% sure I have been passing the arrays and pointers incorrectly (new to them).

The code is below:

#include <stdio.h>
int * array_generator (int number_songs);
int main (void)
{

int input;
int *p;
int i;
int x;


printf("Enter number of songs wanted in random playlist: ");
scanf("%d", &input);

p = array_generator(input);


x = *p;

for (i = 0; i < input; i++)
{

printf("The array contains the values %dn", x);
}   


return 0;
}

int * array_generator (int n)

{
int a[n];
int *p;
int i;

for (i=0; i < n; i++)
    {
    a[i] = i;
    printf("The array contains the values %dn", i);
    }




return p = &a[n];



}


Source: syntax

Leave a Reply