如何在C中将数组初始化为0? [英] How to initialize array to 0 in C?

查看:44
本文介绍了如何在C中将数组初始化为0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个大的 C 中的空数组作为全局数组.除了打字还有什么办法可以做到这一点

I need a big null array in C as a global. Is there any way to do this besides typing out

char ZEROARRAY[1024] = {0, 0, 0, /* ... 1021 more times... */ };

?

推荐答案

全局变量和静态变量自动初始化为零.如果你有简单的

Global variables and static variables are automatically initialized to zero. If you have simply

char ZEROARRAY[1024];

在全局范围内,它在运行时全为零.但实际上,如果您有一个本地数组, 一种速记语法.如果数组已部分初始化,则未初始化的元素会收到相应类型的值 0.你可以写:

at global scope it will be all zeros at runtime. But actually there is a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. You could write:

char ZEROARRAY[1024] = {0};

编译器会用零填充未写的条目.或者,您可以使用 memset 在程序启动时初始化数组:

The compiler would fill the unwritten entries with zeros. Alternatively you could use memset to initialize the array at program startup:

memset(ZEROARRAY, 0, 1024);

如果您更改了它并希望将其重置为全零,这将很有用.

That would be useful if you had changed it and wanted to reset it back to all zeros.

这篇关于如何在C中将数组初始化为0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆