I have been trying to return back an array using the code below -
#include <stdio.h>
int* factor(int num);
int main(void)
{
int num;
printf("\nEnter a number: ");
scanf("%d", &num);
int* array;
array = factor(num);
for(int counter=0; counter<num; counter++)
{
printf("%d\n", array[counter]);
}
}
int* factor(int num)
{
int NumberArray[100];
for(int i=0; i<num; i++)
{
NumberArray[i] = i;
}
return NumberArray;
}
And this has generated the following output -
gcc assignment3func.c -o assignment3func
assignment3func.c: In function ‘factor’:
assignment3func.c:19:1: error: stray ‘\302’ in program
int NumberArray[100];
^
assignment3func.c:19:1: error: stray ‘\240’ in program
assignment3func.c:19:1: error: stray ‘\302’ in program
assignment3func.c:19:1: error: stray ‘\240’ in program
assignment3func.c:23:11: warning: function returns address of local variable [-Wreturn-local-addr]
return NumberArray;
^
Please help me out. I couldn't understand the stray thing.
NumberArrayis scoped within your functionfactor(). Once you leave that scope, it no longer exists and so you are returning a pointer to something that does not exist. You will need to put it on the heap if you want it to survive beyond the scope of the function withmalloc()int NumberArray[100];. 2)int NumberArray[100];-->int *NumberArray = malloc(100*sizeof(*NumberArray));