數組元素全部初始化為同一值問題

來源:互聯網
上載者:User
一:用memset初始化 二:定義資料類型時直接初始化
#include<iostream>#include<cstring>using namespace std;int main(){int a[10],b[10],c[10];        bool map[10][10];memset(a,0x3f,sizeof(a));a[2]=0x3f3f3f3f;        memset(map,false,sizeof(map));//正確 memset(b,0,sizeof(b));memset(c,-1,sizeof(c));//memset(c,2,sizeof(c));錯誤無法將數組初始化為2int d[10]={0};//雖然數組元素全部為0了,但也並不是通過全部初始化為零得到的 int e[10]={-1};//無法將數組全部初始化為-1; cout<<a[0]<<' '<<a[1]<<endl;cout<<a[2]<<endl;cout<<b[0]<<' '<<b[1]<<endl;cout<<c[0]<<' '<<c[1]<<endl;cout<<d[0]<<' '<<d[1]<<endl;cout<<e[0]<<' '<<e[1]<<endl;}

三:數組不初始化的預設值 #include <iostream>   using namespace std;   int a[10];   char b[10];   int main()   {       for (int i = 0; i < 10; i++)            //int全域數組不初始化預設為0       {           cout << a[i];       }       cout << endl;          int c[10];       for (int i = 0; i < 10; i++)            //局部數組不初始化,是隨機值       {           cout << c[i];       }       cout << endl;          int d[10] = { 0 };       for (int i = 0; i < 10; i++)            //為0,未被顯式初始化的元素預設為0,字元數組則是'\0'       {           cout << d[i];       }       cout << endl;          cout << b << endl;                     //按字串方式輸出,輸出為空白,不是空格,可以看出未初始化的全域數組元素為'\0'       for (int i = 0; i < 10; i++)            //單個輸出全為a       {           cout << b[i];       }       cout << endl;          char e[10] = { 'b' };                         cout << e << endl;                     //按字串方式輸出,輸出為b,可見未被顯式初始化的元素為'\0'       for (int i = 0; i < 10; i++)           //char局部數組,單個元素輸出結果為baaaaaaaaa       {           cout << e[i];       }       cout << endl;       char f[10];                            //char局部數組不初始化,輸出為燙燙燙燙燙       for (int i = 0; i < 10; i++)                {           cout << f[i];       }       cout << endl;       return 0;   }  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.