c - Correctly passing an array from a function -


i have code generate array of size [user_input] in function called array_generator, using size of array scanf in main(), , filling numbers 0 user_input (0, 1, 2, 3, if user input 4). array fills correctly printf prints

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

however when pass array main , printf array values equal statements filled garbage numbers. i'm 90% sure have been passing arrays , pointers incorrectly (new them).

the code 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;      (i = 0; < input; i++)     {         printf("the array contains values %d\n", x);     }      return 0; }  int *array_generator(int n) {     int a[n];     int *p;     int i;      (i = 0; < n; i++)     {         a[i] = i;         printf("the array contains values %d\n", i);     }      return p = &a[n]; } 

one simple solution define array bigger largest list of songs reasonably possible. example, since print every entry, more few hundred not reasonable. on modern computer space abundant. have define max size on top of prog, or later in header:

#define max_songlist_len 1000 

the array can global, or can static inside function. let's make static because want function return address.

the change minimal.

static int a[max_songlist_len]; 

you may want change loop , check max length well:

for (i = 0; < input && < max_songlist_len; i++) 

inside array_generator() , main(). may want inform users maximum, , catch numbers large. (you don't error handling of user input anyway -- happens if user enters letter instead of number? return value of scanf().)

the static array's life time lifetime of program. initialized zeroes way. if want randomly initialize @ rand() function.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -