如何用-1初始化全局数组? [英] How to initialize global array with -1?

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

问题描述

如何使用 C 中的 -1 值初始化全局数组?请告诉我。

How to initialize a global array with -1 values in C? Please tell me.

推荐答案

在C中,变量的初始化为其分配了一个初始值,因此,程序开始执行,存储该变量的内存位置包含分配的值。

In C the initialization of a variable is assigning it an initial value so that, even before the program starts its execution, the memory location in which the variable is stored contains the assigned value.

唯一的初始化整数数组的方法它的所有元素的值都将不同于0,正在逐个定义所有元素

The only way to initialize an array of integers so that all its elements will have a value different to 0 is defining all its element one by one:

int arr[5] = { -1, -1, -1, -1, -1 };

这可能很难维护,因为数组很大。另一种方法是在运行时设置值

This could be difficult to maintain is the array is big. The alternative is setting values at runtime.

为了将存储区的所有元素设置为特定值,请 memset 函数可以使用(它在< string.h> 中定义)。

In order to set all elements of a memory area to a specific values, memset function can be used (it is defined in <string.h>). It works great for characters:

char arr [100];

memset (arr, -1, sizeof(arr));

如果您使用整数,仅值-1 ,则可以使用依赖于负值(二进制补码)的二进制表示形式的技巧:在-1中,所有字节均等于 0xFF

If you have integers, just for the value -1, you can use a trick relying on the binary representation of negative values (two's complement): in a -1 all bytes are equal to 0xFF.

int arr [100];

memset (arr, 0xFF, sizeof(arr));

但是,如果您使用不同的类型(例如structs)或不同的值( -1是一个特殊情况),您将不得不使用for循环。

But unfortunately it's not a general solution If you have different types (eg.structs) or different values (-1 is a particular case) you will have to use a for loop.

注意:如果数组是全局数组,则没有特别的约束:初始化相同,并且设置值的方式也相同。在运行时方案中,对于全局数组,您只需要确保在将数组的元素设置为期望值之后执行对数组的每次访问。例如,可以通过执行初始集和 arr_init()函数来获取该信息。

Note: there are not particular constraints if the array is global: the initialization is the same and the way of setting the values is the same as well. In runtime scenario, in case of global arrays, you will just want to make sure that every access to the array is performed after its elements have been set to the expected value. This can be obtained, for example, performing the initial sets an a arr_init() function.

这篇关于如何用-1初始化全局数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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