I have a C program, that’s simple enough, but I’m fairly bad at using pointers intelligently. If anybody could help me with this I’d really appreciate it. It has two functions then the main. The first function creates an array with 10 ints 1-10. The second function prints out that array. Thanks,
#include<stdio.h>
//function to create array of 10 ints
int* myArray(void)
{
int array[10], i;
for(i = 0; i < 10; ++i)
{
array[i] = i + 1;
}
return array;
}
//function to printout the array of 10 ints
void printArray(void)
{
int *array = myArray();
int i;
for(i = 0; i < 10; ++i)
{
printf("%d ", array[i]);
}
}
//my main
int main()
{
myArray();
printArray();
}
The output I currently get is 1 1 2 3078316 5 6 3078824 257921824 1905931270 -2
pretty messed up lol.
The problem is that you are returning a local variable from the function
myArray. Declaringint array[10]will putarrayon the stack, and gets destroyed whenmyArrayreturns. This meansmyArrayis returning an invalid pointer.If you need to create an array within a function, use
malloc. That is:Note that at some point in time in the future you will need to
free()the array. For example, inprintArray: