C Returning an array from a function -
and having trouble grasping arrays in c , how return them via function. if
int main() { int num_set[10]={0,1}; //initialize first 2 elements 0,1 , rest 0 int* p=num_set; //assign array int pointer called p printf("\n%i",&num_set); //outputs 2686660 on machine printf("\n%i",&num_set[0]); //also outputs 2686660 printf("\n%i",p); //also outputs 2686660 printf("\n%i",p[1]);* //outputs 0; same num_set[1] }
it works expected, when try return array through function following
int multiply_by_2(int given_number) { int num_set[10]; for(int fun_counter=0; fun_counter<10; fun_counter++) { num_set[fun_counter] = (given_number*2) ; } return num_set; //return int array num_set caller } int main() { int* p = multiply_by_2(300) //assign array returned function p for(int main_counter=0; main_counter>10; main_counter++) { printf("\np[%i] = %i" , i, p[i]); } }
i error saying "invalid conversion 'int' 'int*'"
they no error when assigned array int pointer in first code, error when try return through function.
please help.
there number of errors here.
the return type of function
multiply_by_2
needsint*
- i.e pointer integer. returned pointer first element of array.you attempting return variable initialized on stack (
num_set
). disappearmultiply_by_two
function exits, because automatic variable. instead, should usemalloc
function allocate heap memory. here's link explaining difference between stack , heap memoryyou have
>
should have<
infor
loop inmain
. written loop exit.minor point - number 10 repeated several times throughout code. better practice use variable or
#define
give number meaningful name
here's amended version of code:
#include <stdio.h> #include <stdlib.h> //this required use malloc #define array_size 10 int* multiply_by_2(int given_number) { int *num_set =malloc(sizeof(int)*array_size); for(int fun_counter=0; fun_counter<array_size; fun_counter++) { num_set[fun_counter] = (given_number*2) ; } return num_set; //return int array num_set caller } int main() { int* p = multiply_by_2(300); //assign array returned function p for(int i=0; i<array_size; i++) { printf("\np[%i] = %i", i, p[i]); } free(p); }
Comments
Post a Comment