c - How do I get my array to return an int array to be used in another function? -
i need function drop_balls return array can make next function use array. need take in integer parameter, , return int array can used in function making after. have been reading can passed pointer, have absolutely no idea how coded, can please me out.
#include <stdio.h> #include <stdlib.h> #include <time.h> /* prototype drop_balls, int parameter number of balls being dropped */ int [] drop_balls(int); /* gets number of balls need dropped user */ int get_num_balls(); int main() { drop_balls(get_num_balls()); } int get_num_balls() { int num_balls; printf("how many balls should dropped? "); scanf("%d", &num_balls); /* ensure atleast 1 ball */ while(num_balls <= 0) { printf("you have drop @ least 1 ball! \n "); printf("how many balls should dropped? "); scanf("%d", &num_balls); } /* return number of balls dropped */ return num_balls; } int [] drop_balls(int num_balls) { /* keeps track of how many balls landed */ int ball_count[21]; /* number ball on */ int ball_num = 0; /* seed generator */ srand(time(null)); /* correct # of balls */ for(ball_num = 0; ball_num < num_balls; ball_num++ ) { /* start @ 10 since middle of 21 */ int starting_point = 10; /* bounce each ball 10 times */ for(starting_point = 10; starting_point > 0; starting_point--) { int number; /* create random integer between 1-100 */ number = rand() % 100; /* if less 50 bounce right once */ if(number >= 50) { starting_point++; } /* if greater 50, bounce left once */ else { starting_point--; } } /* add 1 simulate 1 ball landing there */ ball_count[starting_point]++; } return ball_count; }
it not sure want achieve, if want pass array of integers balls
function drop_balls
declared so:
void drop_balls(int **balls); int main () { int *balls; /* array of balls*/ /* allocate memory `number_of_balls` number of balls */ balls = malloc(number_of_balls * sizeof(*balls)); if (balls == null) printf("error: failed allocate memory"); /* call function passing pointer array of balls */ drop_balls(&balls); free(balls); return 0; }
Comments
Post a Comment