0

Do array of structure pointers point to NULL automatically/without being initialized? I would assume not, but it seems to be operating in that manner in the following line of code:

for (np = hashtab[hash(s)]; np != NULL; np = np->next)

np is a structure pointer, and s is a string.

None of the elements in hashtab[] have even been initialized when the loop begins. Every time I run the program the loop terminates immediately because hashtab[] contains NULL

The full code is below.

struct nlist {       /* table entry: */
    struct nlist *next;   /* next entry in chain */
    char *name;           /* defined name */
    char *defn;           /* replacement text */
};

unsigned hash(char *s)
{
    unsigned hashval;

    for (hashval = 0; *s != '\0'; s++)
        hashval = *s + 31 * hashval;
    return hashval % HASHSIZE;
}

/* lookup:  look for s in hashtab */
struct nlist *lookup(char *s)
{
    struct nlist *np;
    for (np = hashtab[hash(s)]; np != NULL; np = np->next)
    if (strcmp(s, np->name) == 0)
        return np;     /* found */
    return NULL;           /* not found */
}
1
  • 1
    How and where is hashtab defined? Commented Sep 25, 2014 at 18:52

3 Answers 3

2

calloc() function will initialize the memory with zeroes.

#include <stdio.h>
char array[100]; // - initialized by zeroes
void main(void)
{
    char array2[100]; // - initialized with random values
    static char array3[100]; // - initialized by zeroes and allocate not in the stack
}
Sign up to request clarification or add additional context in comments.

Comments

1

Since hashtab is global, it is initialized with default values (assuming it's an array and not a dynamically allocated pointer), including NULL for pointer types. This is only for globals or locals declared static.

Comments

1

Well, where is hashtab defined? I don't see its definition in the code you posted.

If hashtab array is an object with static storage duration, then it is guaranteed to be zero-initialized at program startup. Otherwise, it is not initialized at all. All objects with static storage duration are zero-initialized at program startup.

The code you posted suggests that hashtab is defined as an external object, which probably means that it is indeed an array with static storage duration. That explains why it is initialized with null pointers by default.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.