字符串数组

#include <iostream>
using namespace std;

int main(int argc, const char * argv[]) {
    //用数组指针遍历而为数组,纬度为字符串最大长度+1(即\0)
    //最长的列是6
    char s[][6] = {"hello","world","good","bye"};
    char (*p)[6] = s;
    for (int i =0; i<4; i++,p++) {
        cout<<*p<<endl;
    }
    return 0;
}
hello
world
good
bye

虽然能正确输出字符串,但是有些浪费内存,有没有更好的办法呢?

指针数组:存放每个字符串的地址

方法二:

#include <iostream>
using namespace std;

int main(int argc, const char * argv[]) {    
    //指针数组
    char *s[] = {"hello","world","good","bye"};
    cout<<"sizeof(s):"<<sizeof(s)<<endl;
    cout<<"sizeof(s[0]):"<<sizeof(s[0])<<endl;
    cout<<"sizeof(s[1]):"<<sizeof(s[1])<<endl;
    cout<<"sizeof(s[2]):"<<sizeof(s[2])<<endl;
    cout<<"sizeof(s[3]):"<<sizeof(s[3])<<endl;
    for (int i=0; i<sizeof(s)/sizeof(s[0]); i++) {
        cout<<s[i]<<endl;
    }
    return 0;
}
sizeof(s):32
sizeof(s[0]):8
sizeof(s[1]):8
sizeof(s[2]):8
sizeof(s[3]):8
hello
world
good
bye

可以看到每一个字符指针长度都是固定

results matching ""

    No results matching ""