I'm studying C and reading this
#include <stdio.h>
#include <time.h>
/* function to generate and retrun random numbers. */
int * getRandom( ) {
static int r[10];
int i;
/* set the seed */
srand( (unsigned)time( NULL ) );
for ( i = 0; i < 10; ++i) {
r[i] = rand();
printf("%d\n", r[i] );
}
return r;
}
/* main function to call above defined function */
int main () {
/* a pointer to an int */
int *p;
int i;
p = getRandom();
for ( i = 0; i < 10; i++ ) {
printf("*(p + [%d]) : %d\n", i, *(p + i) );
}
return 0;
}
The article explains that, since a pointer declared in a function is a local variable, hence it has to be defined as 'static'. (line 7, variable r)
There are three points I'm concerned.
Firstly, "static int r[10]" declares that they want to create an int array of size 10. When it's returned from the getRandom function with "return r", the function actually returns the address of the first member of r[10], or the pointer to the first address of r[10]?
Secondly, in main function, p = getRandom() means the address or pointer returned from getRandom() is assign to pointer p. Eventhough r will poof as soon as getRandom() stops working, the address would have been already assigned to p. So, why is it needed to be declared as static?
Or getRandom() returns address to the pointer pointing to r[10], hence when disappear, p would point to empty address not to r[10]?
Or, not only pointer to r, but also r[10] array would disappear when getRandom() stops, so it's needed to be static?
Thirdly, is it correct that, variables in any function declared without malloc would be stored as stack memory?
gcc -Wall -Wextra -gif using GCC...) and run your example step by step in a debugger (gdb) and query the value of interesting variablesgetRandom()at least three times in a row and compare the numbers it emits...