#include<iostream>intmain(){intarray[]{9,7,5,3,1};std::cout<<"Element 0 is at address: "<<&array[0]<<'\n';std::cout<<"Element 1 is at address: "<<&array[1]<<'\n';std::cout<<"Element 2 is at address: "<<&array[2]<<'\n';std::cout<<"Element 3 is at address: "<<&array[3]<<'\n';return0;}
在笔者的电脑上会打印如下信息:
1234
Element 0 is at address: 0041FE9C
Element 1 is at address: 0041FEA0
Element 2 is at address: 0041FEA4
Element 3 is at address: 0041FEA8
注意,每个地址之间都间隔4字节,这正是笔者电脑上整型数的大小。
指针算数、数组和索引背后的魔法
上面已经介绍了,数组是一系列顺序排列的内存。
在之前的课程中我们还介绍了,固定数组可以退化为指针,该指针指向数组的第一个元素。
同时我们还知道,对指针加1可以得到该指针所指地址后面一个对象的地址。
以你,对数组加1就可以得到第二个元素,通过下面的代码可以进行验证:
1 2 3 4 5 6 7 8 91011121314
#include<iostream>intmain(){intarray[]{9,7,5,3,1};std::cout<<&array[1]<<'\n';// print memory address of array element 1std::cout<<array+1<<'\n';// print memory address of array pointer + 1std::cout<<array[1]<<'\n';// prints 7std::cout<<*(array+1)<<'\n';// prints 7 (note the parenthesis required here)return0;}
#include<iostream>#include<iterator> // for std::sizeboolisVowel(charch){switch(ch){case'A':case'a':case'E':case'e':case'I':case'i':case'O':case'o':case'U':case'u':returntrue;default:returnfalse;}}intmain(){charname[]{"Mollie"};intarrayLength{static_cast<int>(std::size(name))};intnumVowels{0};for(char*ptr{name};ptr!=(name+arrayLength);++ptr){if(isVowel(*ptr)){++numVowels;}}std::cout<<name<<" has "<<numVowels<<" vowels.\n";return0;}
#include<algorithm>#include<iostream>#include<iterator> // for std::begin and std::endboolisVowel(charch){switch(ch){case'A':case'a':case'E':case'e':case'I':case'i':case'O':case'o':case'U':case'u':returntrue;default:returnfalse;}}intmain(){charname[]{"Mollie"};// walk through all the elements of name and count how many calls to isVowel return trueautonumVowels{std::count_if(std::begin(name),std::end(name),isVowel)};std::cout<<name<<" has "<<numVowels<<" vowels.\n";return0;}
// nameLength is the number of elements in the array.std::count_if(name,name+nameLength,isVowel)// Don't do this. Accessing invalid indexes causes undefined behavior.// std::count_if(name, &name[nameLength], isVowel)