当前位置: 代码迷 >> 综合 >> 将整型数组元素初始化为0的方法
  详细解决方案

将整型数组元素初始化为0的方法

热度:37   发布时间:2024-02-25 09:07:43.0

将整型数组元素初始化为0的方法:

第一种方法

       对于局部数组我们还有简写的初始化语法。如果一个数组被部分初始化,没有被初始化的元素会被自动设置为相应类型的0。这是编译器自动完成的。

源代码如下:

#include <iostream>
using namespace std;int main() {//将数组置初值为0d的第一种方法:int a[10] = {0};for (int i = 0; i < 10;i++) {cout << a[i] << " ";}cout << endl;system("pause");return 0;
}

输出结果为:

0 0 0 0 0 0 0 0 0 0
请按任意键继续. . .

第二种方法的源代码如下:

#include <iostream>
using namespace std;int main() {//第二种初始化方法int a[10] = { 0,0,0,0,0,0,0,0,0,0 };for (int i = 0; i < 10; i++) {cout << a[i] << " ";}cout << endl;system("pause");return 0;
}

输出结果为:

0 0 0 0 0 0 0 0 0 0
请按任意键继续. . .

第三种方法  用memset函数

      memset:作用是在一段内存块中填充某个给定的值,它是对较大的结构体或数组进行清零操作的一种最快方法

      注意:memset函数按字节对内存块进行初始化,所以不能用它将int数组初始化为0和-1之外的其他值(除非该值高字节和低字节相同)。

源代码如下:

#include <iostream>
using namespace std;int main() {int a[10];memset(a,0,sizeof(a));//memset(a, -1, sizeof(a));//memset函数按字节对内存块进行初始化,所以不能用它将int数组初始化为0和-1之外的其他值(除非该值高字节和低字节相同)。for (int i = 0; i < 10; i++) {cout << a[i] << " ";}cout << endl;system("pause");return 0;
}

输出结果为:

0 0 0 0 0 0 0 0 0 0
请按任意键继续. . .

第四种方法 用循环的方法进行赋值

源代码如下:

#include <iostream>
using namespace std;int main() {int a[10];//用循环的方法进行赋值for (int i=0; i < 10;i++) {a[i] = 0;}//循环进行输出,检验是否正确cout << "赋值的结果为:" << endl;for (int i = 0; i < 10;i++) {cout << a[i]<<" ";}cout << endl;system("pause");return 0;
}

输出结果为:

0 0 0 0 0 0 0 0 0 0
请按任意键继续. . .

  相关解决方案