1.字符数组未初始化里面元素值为多少
(1)字符数组定义在main函数外面,s[i]的值为’\0’即为NULL(i=0,1,2,3…), (int)s[i]的值为0。
#include<iostream>
using namespace std;
char s[5];
int main()
{
for(int i=0; i<5; ++i)
{
if(s[i]=='\0')//s[i]==0,s[i]==NULL都行
cout << "I'm coming home,Ace!" << endl;
}
return 0;
}
#include<iostream>
using namespace std;
char s[5];
int main()
{
for(int i=0; i<5; ++i)
{
cout << (int)s[i];
}
return 0;
}
(2)字符数组定义在main函数里面,输出结果表现为乱码,(int)s[i]的值为随机数。
#include<iostream>
using namespace std;
int main()
{
char s[5];
for(int i=0; i<5; ++i)
cout << s[i];
cout << "End!" << endl;
for(int i=0; i<5; ++i)
cout << (int)s[i] << ' ';
return 0;
}
2.字符数组在部分初始化后,后面的元素自动赋值为’\0’
#include<iostream>
using namespace std;
int main ()
{
char s[10]="abcde";
//char s[10]={"abcde"};
//char s[10]={'a','b','c','d','e'};//三种初始化方式都一样
for(int i=0; i<10; i++)
{
if(s[i]=='\0')
cout << '0';
else
cout << s[i];
}
return 0;
}
//输出结果为:abcde00000
注意:
#include<iostream>
using namespace std;
int main()
{
char s[10];
s[0]='a'; //这种类型不属于初始化,而是赋值
s[1]='b'; //等价于未初始化的数组,只是将其前五个数进行了赋值
s[2]='c'; //其余元素仍为乱码
s[3]='d'; //输出(int)s[i]为随机数(前五个数为 abcde 的 ASCII 码)
s[4]='e';
for(int i=0; i<10; i++)
{
cout << s[i];
}
cout << endl;
for(int i=0; i<10; i++)
{
cout << (int)s[i] << ' ';
}
return 0;
}
/*
输出结果:
第一行为乱码
第二行前五个数为 abcde 的 ASCII码,其余数为随机数
*/
3.字符数组初始的值全部置为’\0’的办法(即以%c读取为NULL即空,以%d读取为0)
(1)内存操作库函数memset
头文件cstring中声明:
void * memset(void * dest,int ch,int n);
将从dest开始的n个字节,都设置成ch。返回值是dest。ch只有最低的字节起作用。
例:将szName的前10个字符,都设置成’a’:
char szName[200] = “”;
memset( szName,‘a’,10);
cout << szName << endl;
=>aaaaaaaaaa
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char s[10];
memset(s,'\0',10);
for(int i=0; i<10; ++i)
{
if(s[i]=='\0')
cout << (int)s[i];
}
return 0;
}
//输出为 0000000000
(2)char s[10]={0},从一开始就全部赋值为0
#include<iostream>
using namespace std;
int main()
{
char s[10]={0};
for(int i=0; i<10; ++i)
{
if(s[i]=='\0')
cout << (int)s[i];
}
return 0;
}
//输出为 0000000000
这样只要对字符数组进行连续赋值,便很容易通过下列代码遍历输出整个字符数组,而不用管字符数组的长度为多少:
#include<iostream>
using namespace std;
int main()
{
char s[20]="Cayde 6";
int i=0;
while(s[i]!='\0')
{
cout << s[i++];
}
return 0;
}
//输出 Cayde 6
参考:https://blog.youkuaiyun.com/weixin_38481963/article/details/79477903
感谢观看!