数组 长度,指针指向数据的长度

有一次面试写程序,就排序之类的,需要先知道一串数据的长度,

若数据是数组形式,

int q[]={1,2,3};

lq=sizeof(1)/4;// sizeof()表示栈大小。

若是指针形式

int *pq=q;

则没有直接的方式知道指针pq的长度。

若是vector<int> vp;

vp.size();返回容器vp可容纳的最多元素个数。

但那次面试,我居然写了length()!!!!大囧!

std::string::length()
size_t length() const;
举例:string str("abab");
cout<<str.length()<<endl;

对字符串求长度还可以有string::size(). 两者功能一样,都表示字符串实际含有的字符个数,而不是字符串的空间。
"Returns the length of the string, in terms of number of characters.

This is the number of actual characters that conform the contents of the string, which is not necessarily equal to its storage capacity.

Both string::size and string::length are synonyms and return the same value."
再谈谈strlen() ,他是C string 中返回 字符串从开始到' '前的字符的个数,与c++中的length() 功能一样。

再说说 字符串string 不是数组,变量名不能代表地址。
string s("abbb");
char *ps=&s;//not char* ps=s;
char []ss="abbb";
ps=ss;
char s1[]=s.tocharArray();
ps=s1;