And having some trouble grasping arrays in C and how to return them via a function. If I do something like this
int main()
{
int num_set[10]={0,1}; //initialize first two elements as 0,1 and rest as 0
int* p=num_set; //assign array to int pointer called p
printf("\n%i",&num_set); //outputs 2686660 on my machine
printf("\n%i",&num_set[0]); //also outputs 2686660
printf("\n%i",p); //also outputs 2686660
printf("\n%i",p[1]);* //outputs 0; the same as num_set[1]
}
It works as expected, but when I try to return an array through another function like the 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 to caller
}
int main()
{
int* p = multiply_by_2(300) //assign array returned by function to p
for(int main_counter=0; main_counter>10; main_counter++)
{
printf("\np[%i] = %i"
, i, p[i]);
}
}
I get an error saying "invalid conversion from 'int' to 'int*'"
They was no error when I assigned the array to an int pointer in the first code, but I get this error when I try to return it through a function.
Please help.
multiply_by_2to return anint, but you're trying to return anint[10].