如何将数组的所有元素设置为零或任何相同的值?

use*_*709 10 c linux arrays

我是C的初学者,我真的需要一种有效的方法来设置数组的所有元素等于零或任何相同的值.我的数组太长了,所以我不想用for循环来做.

aja*_*jay 17

如果您的阵列具有静态存储分配,则默认将其初始化为零.但是,如果数组具有自动存储分配,则可以使用包含零的数组初始值设定项列表将其所有元素初始化为零.

// function scope
// this initializes all elements to 0
int arr[4] = {0};
// equivalent to
int arr[4] = {0, 0, 0, 0};

// file scope
int arr[4];
// equivalent to
int arr[4] = {0};
Run Code Online (Sandbox Code Playgroud)

请注意,没有标准方法可以使用包含单个元素(值)的初始化列表将数组元素初始化为零以外的值.您必须使用初始化列表显式初始化数组的所有元素.

// initialize all elements to 4
int arr[4] = {4, 4, 4, 4};
// equivalent to
int arr[] = {4, 4, 4, 4};
Run Code Online (Sandbox Code Playgroud)


小智 7

int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; // All elements of myArray are 5
int myArray[10] = { 0 };    // Will initialize all elements to 0
int myArray[10] = { 5 };    // Will initialize myArray[0] to 5 and other elements to 0
static int myArray[10]; // Will initialize all elements to 0
/************************************************************************************/
int myArray[10];// This will declare and define (allocate memory) but won’t initialize
int i;  // Loop variable
for (i = 0; i < 10; ++i) // Using for loop we are initializing
{
    myArray[i] = 5;
}
/************************************************************************************/
int myArray[10] = {[0 ... 9] = 5}; // This works only in GCC
Run Code Online (Sandbox Code Playgroud)


Saw*_*wan 5

如果你确定长度,你可以使用memset.

memset(ptr,0x00,长度)