When a function terminates, then all its automatic variables go out of scope.
tab
is an automatic variable in this case, and will go out of scope when the function terminates. Now you are returning a pointer to a local array, so when the array goes out of scope, you will find yourself with a dangling pointer.
Didn't your compiler warned you about this? I got, in GCC, this warning:
warning: function returns address of local variable [-Wreturn-local-addr]
return tab;
^~~
First make sure that you really want for practicing to create the array in the function. If not, then you don't need to, you could just create in main, and then pass it to the function.
But, if you want to practice, then you need to dynamically allocate the array, if you really want it to stay alive after the function terminates. In that case, the array will free its memory, only when you tell it to (so never forget to free).
Example:
#include <stdio.h>
#include <stdlib.h>
int* tabinit(int size) {
int *tab = malloc(size * sizeof(int));
for (int i = 0; i < size; i++)
tab[i] = 0;
return tab;
}
int main() {
int* t = tabinit(10);
for (int i = 0; i < 10; i++)
printf("%d ", t[i]);
printf("\n");
// do NOT forget to free
free(t);
return 0;
}
Output:
0 0 0 0 0 0 0 0 0 0
PS: When you get more familiar with malloc()
, I suggest you read this: Should I check if malloc() was successful?