Reputation: 21
I am currently taking the CS50x couse by Harvard and ran across the following problem.
In the short excerpt below, is hashtable[i] set to null by default? I am under the impression that when I allocate enough memory for 10 nodes (as in below), I should get 10 different addresses rather than null pointers. However, the course I am taking seem to suggest that even though I am allocating enough memory for 10 nodes, they won't be assigned addresses immediately. Instead, they will be assigned null pointers.
typedef struct node
{
char word[N + 1];
struct node *next;
}
node;
node *hashtable[10];
Upvotes: 1
Views: 195
Reputation: 310960
Whether the elements of the array
node *hashtable[10];
will be initialized by a null pointer or not depending on where the array is declared.
If the array has automatic storage duration that is if it is declared in a code block within a function then its elements are not initialized and have indeterminate values.
If the array is declared in a file scope (outside any function) then it has static storage duration and its elements are initialized by a null pointer.
From the C Standard (6.7.9 Initialization)
10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:
— if it has pointer type, it is initialized to a null pointer; ...
— if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
Upvotes: 2
Reputation: 11377
The initialization of the hashtable array depends on where and how it is declared. If hashtable is declared outside of a function, each element is initialized to NULL (which essentially points to nothing). This is also true if hashtable is declared inside a function and has the storage class static. The only difference between the two is that the latter can only be accessed inside the function.
node *hashtable[10]; /*each element is initialized to NULL*/
void f(void)
{
static node *hashtable[10]; /*each element is initialized to NULL*/
...
}
If hashtable is declared inside a function and does not have the storage class static (i.e. is a regular local variable), each element is undefined which in practice means that it could have any value:
void g(void)
{
node *hashtable[10]; /*each element is undefined*/
...
}
The reason for this difference is that variables which exist during the whole lifetime of the program can be initialized for free by the compiler; the variable is compiled into the executable. On the other hand, initializing a local (non-static) variable needs to be performed each time a function is called and is therefor associated with a run-time cost.
Upvotes: 0