字符数组和字符串数组"\0"问题

//字符数组
#include <iostream> #include <string.h> using namespace std; int main(int argc, char const *argv[]) { char x[] = "abcdefg"; //字符串存储会默认后面加一个字符“\0” char y[] = {'a','b','c','d','e','f','g'};      //单字符存储则不会有“\0” cout << sizeof(x) << endl;   //sizeof 计算实际存储的字节数,包括"\0"            cout << sizeof(y) << endl;   // cout << strlen(x) << endl;   //strlen计数器,逐个计算所有遍历的字符不包括“\0” cout << strlen(y) << endl; //输出14 = y[]的7 + x[] 的7 return 0; }

zl@LAPTOP-2ABL2N6V:/mnt/d/基础入门/08-数据结构$ g++ 1.cpp -o 1
zl@LAPTOP-2ABL2N6V:/mnt/d/基础入门/08-数据结构$ ./1
8
7
7
14
zl@LAPTOP-2ABL2N6V:/mnt/d/基础入门/08-数据结构$

  经过仔细研究发现:cout << strlen(y) << endl; //输出14 = y[]的7 + x[] 的7  有很多人有疑问
  实际上我们也知道 strlen就是逐个计算字符直到'\0'为止,
      strlen(y) 计算为 7        但是这个时候还不算完,因为没扫描的'\0'  机器还有继续扫描;
      从上往下,从先往后选择目标字符串长度(带上'\0')大于y[]的字符串长度的字符串继续扫描,找到了x[]  7  ,也扫描到了'\0',结束扫描
      共计计数  7 + 7 =14
  总结:strlen计数时,如果一次计数完成未找到'\0',计数不会停止,
      这个时候他会继续顺序寻找其他(带上'\0')更长的数组继续计数,继续计数并寻找'\0',重复下去,
        直到找到'\0'结束计数,或者找不到其他(带上'\0')更长的数组,也会停止计数。
        字符串数组 
x[] = "abcdefg"; 这样的会默认有\0 strlen计数不计算,但站字符长度(sizeof可测),带上'\0'表示的就是长度算上隐藏的'\0'

//字符数组
#include <iostream>
#include <string.h>
using namespace std;
int main(int argc, char const *argv[])
{
    
    char b[] = {'a','b','d','f'};    //4    大于3
    char c[] = {'a','b','d','d'};    //4    大于3
    char x[] = "bdc";                //3    计数为4大于3
    char a[] = "a";
    char y[] = {'a','b','c'};        //3
  //  cout << sizeof(x) << endl;     
  //  cout << sizeof(y) << endl;
  //  cout << strlen(x) << endl;
    cout << strlen(y) << endl;       //输出14
    return 0;
}

 

 

 

 

 

posted @ 2021-11-26 15:23  尘落曦枫  阅读(708)  评论(0)    收藏  举报