typedef struct TestMap TestMap;
struct TestMap {
int k;
int v;
};
int main(){
int **test = (int **)malloc(sizeof(int*) * 2);
if (test[0] == NULL)
printf("without memset: test[0]==NULL\n");\\不显示
free(test);
TestMap **tm = (TestMap **)malloc(sizeof(TestMap*) * 2);
if (tm[0] == NULL)
printf("without memset: tm[0]==NULL");\\不显示
free(tm);
int **test = (int **)malloc(sizeof(int*) * 2);
memset(test, 0, sizeof(int*) * 2);
if (test[0] == NULL)
printf("with memset: test[0]==NULL\n");\\显示
free(test);
TestMap **tm = (TestMap **)malloc(sizeof(TestMap*) * 2);
memset(tm, 0, sizeof(TestMap*) * 2);
if (tm[0] == NULL)
printf("with memset: tm[0]==NULL");\\显示
free(tm);
return 0;
}
输出
不显示原因
显示原因
可以看到,通过memset的初始化,统一野值为NULL。值得注意的是,自定义结构也可以通过memset(对象, 0, 空间大小)的方式初始化,函数使用此值的无符号字符转换填充内存块。