C++中计算字符串数组元素的个数方法与原因分析

Keep Open and Learning
Post Reply
星际浪子
Posts: 3597
Joined: 01 May 2009 23:45

C++中计算字符串数组元素的个数方法与原因分析

Post by 星际浪子 » 05 Jul 2011 08:30

1. 先写上方法吧,如下

#include <iostream>
#include <string>
using namespace std;

int main()
{
string str[] = {"abfafawfefw","defg","32121","Miss","11111"};
cout << sizeof(str) / sizeof(str[0]);
return 0;
}

2. 原因分析

字符串数组存取方式采用了对齐原则,占用空间少的向占用空间多的靠齐,首先使用sizeof(str)首先获得所用的所用字节数,使用sizeof(str[0])再计算数组中一个元素平均占用的字节数。所以除一下,得到个数,搞定!

Post Reply