我是一个C语言的初学者,我真的需要一种有效的方法来将数组中所有元素设置为零或任何相同的值。我的数组非常长,因此我不想使用for循环来完成。
我是一个C语言的初学者,我真的需要一种有效的方法来将数组中所有元素设置为零或任何相同的值。我的数组非常长,因此我不想使用for循环来完成。
如果您的数组有静态存储分配,则默认初始化为零。然而,如果该数组具有自动存储分配,则可以使用包含零的数组初始化器列表来简单地将其所有元素初始化为零。
// 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};
请注意,使用仅包含单个元素(值)的初始化器列表初始化数组元素为非零值时,没有标准方法可供使用。您必须使用初始化程序列表显式初始化数组的所有元素。// initialize all elements to 4
int arr[4] = {4, 4, 4, 4};
// equivalent to
int arr[] = {4, 4, 4, 4};
int x[] = { 1, 3, 5 };
不算作单个语句的初始化吗? - Peter - Reinstate Monica如果您确定长度,可以使用memset。
memset(ptr, 0x00, length)
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