天天看點

數組

數組表示一類資料的集合

#include<iostream>

int main()
{
    int example[5];
    int *ptr = example;
    for (int i = 0; i < 5; ++i)
    {
        example[i] = 2;
    }
    example[2] = 5;
    *((int*)((char*)ptr + 8)) = 6;

    std::cin.get();
}      

在強制類型轉換那一行代碼加上斷點進行調試,輸入首位址example檢視記憶體

 可以看到四個位元組為一組,組成了數組example的記憶體位址

 按下f10後發現example[2]中的值改變了

數組

 因為char是字元類型,一個位元組(byte),int整型4位元組,是以将整型指針ptr進行強制類型轉換,轉換成字元型時,想要通路原來數組的第三個元素,就要在首位址的基礎上向後移動2個int大小的空間,也就是8個char的空間,然後再強轉回int進行指派。

#include<iostream>

int main()
{
    int example[5];//在棧上建立
    int *another = new int[5];//在堆上建立,生命周期不同上面數組,需要用delete删除
    delete[] another;
    std::cin.get();
}      

以記憶體的方式來看這兩種方法的不同,new int[5];這種方式更像是間接存儲,example直接就是數組首位址,但是another不是,another是一個指針,指向後面申請的五個連續記憶體位址的首位址。

#include<iostream>

class Entity
{
public:
    int example[5];
    Entity()
    {
        for (int i = 0; i < 5; i++)
        {
            example[i] = 2;
        }
    }
};
int main()
{
    Entity e;

    std::cin.get();
}      

此時輸入"&e"可以直接看到記憶體中的數組,所有的值經過構造函數都指派為2

數組

用new來建立數組

#include<iostream>

class Entity
{
public:
    int *example=new int[5];
    Entity()
    {
        for (int i = 0; i < 5; i++)
        {
            example[i] = 2;
        }
    }
};
int main()
{
    Entity e;

    std::cin.get();
}      

進入調試,輸入&e來檢視記憶體,發現記憶體中存儲的并不是5個2,而是一串位址

數組

 這就是example中存儲的,new新申請的五個記憶體空間的首位址,輸入這個位址進行檢視,看到了new int[5]中存儲的5個2

數組
#include<iostream>
#include<array>

class Entity
{
public:
    static const int exampleSize = 5;
    int example[exampleSize];

    std::array<int,5> another;//c++11

    Entity()
    {
        for (int i = 0; i < another.size(); i++)
        {
            another[i] = 2;
        }
    }
};
int main()
{
    Entity e;

    std::cin.get();
}      
上一篇: 數組
下一篇: 數組