C++數組

來源:互聯網
上載者:User

標籤:

數組(array)是一種資料格式,能夠儲存多個同類型的值。

 

下面貼出代碼:

 

#include<iostream>

int main()
{
using namespace std;
int yams[3];
yams[0] = 7;
yams[1] = 8;
yams[2] = 6;

int yamcosts[3] = {20,30,50};
//yamcosts[3] = {20,30,50}; //not allowed;
//yams = yamcosts; //not allowed;
float fa[5] = {0.5f,2.3f} ; //只初始化一部分元素,則編譯器將其他元素置為0
float fb[5] = {0.0}; //將所有元素都置為0
cout<<yams[0]<<" "<<yams[1]<<" "<<yams[2]<<endl;
cout<<yamcosts[0]<<" "<<yamcosts[1]<<" "<<yamcosts[2]<<endl;

cout<<sizeof yams<<endl;
cout<<sizeof yams[0]<<endl;
cout<<fa[3]<<endl;

short test[] = {2,5,97,4};
int num_elements = sizeof test/sizeof (short);//當不關心數組元素個數時,這是一種很好的解決方案。
cout<<num_elements<<endl;

return 0;
}

 

 

擴充:

1、數組之所以被稱為複合類型,是因為他是使用其他類型來建立的。不能僅僅將某種東西聲明為數組,它必須是特定類型的數組。類如:flaot loans[20],其中loans的類型是float數組而不是數組。

2、有效下標的重要性。編譯器不會檢查下標是否有效。例如,如果將一個值賦給不存在的元素months[101],編譯器並不會報錯。但這種賦值可能破壞資料,也可能導致程式異常終止。所以必須確保程式使用有效下標值。

C++數組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.