【memset()应用】C语言初始化自定义结构的野值

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, 空间大小)的方式初始化,函数使用此值的无符号字符转换填充内存块。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值