gpt4 book ai didi

c - 自动指向 NULL 的结构指针数组?

转载 作者:太空宇宙 更新时间:2023-11-04 06:26:40 25 4
gpt4 key购买 nike

结构指针数组是否自动/未初始化指向 NULL?我假设不是,但它似乎在以下代码行中以这种方式运行:

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

np是结构体指针,s是字符串。

hashtab[] 中的所有元素甚至在循环开始时都没有被初始化。每次我运行程序时,循环都会立即终止,因为 hashtab[] 包含 NULL

完整代码如下。

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 */
}

最佳答案

calloc() 函数将用零初始化内存。

#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
}

关于c - 自动指向 NULL 的结构指针数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26045945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com