1-数组的两种不同的初始化方法:
- 1 声明数组时
int arr[] = {1, 2, 3, 4, 5};
- 2 声明后初始化数组
int arr[5];
for(int i=0;i<5;i++){
arr[i]=i+1;
}
2-如果未初始化会怎样?
如果数组声明后未初始化,则它将会在每个内存位置包含一些随机值。这些随机值可能会有两种类型:
1.默认值
1 如果数组元素是object类型,则默认值为null。
java
import java.io.*;
class GFG {
public static void main(String[] args)
{
Integer[] array = new Integer[5];
for (Integer p : array) {
System.out.print(p + " ");
}
}
}
Python3
# code
arr = [None]*5
print(arr)
#this code is contributed by Akshay Tripathi(akshaytripathi630)
输出
null null null null null
2 如果数组元素是原始数据类型,则默认值为0
java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int[] array = new int[5];
for (int p : array) {
System.out.print(p + " ");
}
}
}
Python3
# code
arr = [0]*5
print(arr)
#this code is contributed by Akshay Tripathi(akshaytripathi630)
C#
using System;
public class GFG
{
static public void Main (){
int[] array = new int[5];
foreach (int p in array)
{
Console.Write(p + " ");
}
}
}
// This code is contributed by akashish__
输出
0 0 0 0 0
2 垃圾值
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int array[5];
for (int p : array)
cout << p << " ";
return 0;
}
Javascript
<script>
let arr = new Array(5);
for(x of arr){
document.write(x + "<br>");
}
</script>
输出
undefined
undefined
undefined
undefined
undefined