icp/oer/courses/c-basics/sections/24-dynamic-memory/02-heap/program.c

32 lines
766 B
C

#include <stdio.h>
#include <stdlib.h>
#include "fib.h"
// TODO: Fix this function.
int* BuildFibArray(int n)
{
int Numbers[n];
for (int x = 0; x < n; x++) {
Numbers[x] = fib(x);
}
int *Array = Numbers;
return Array;
}
int main(int argc, const char *argv[])
{
int *fibs = BuildFibArray(10);
// Doing some stuff that could overide the values we point to
fib(5);
printf("Fib: ");
for (int i = 0; i < 10; i++)
printf("%d, ", fibs[i]);
printf("\n");
// As you noticed this doesn't print out the right numbers
// That is because, when we return from the function, the array is no longer allocated.
// So the pointer points to just garbage. If we are lucky nothing did overwrite the values, but normaly thats not the case.
}