您的位置:首页 > 其它

关于字符变量的一些总结

2014-10-17 16:23 106 查看
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">char 表示的是一个字符变量,可以按照这种方式定义: char ch1='a';</span>


char* 表示的是一个字符类型指针,可以按照如下方式定义:char* ch1="abcd"; 这里ch1存储的是该字符串文字量的a的指针,实验如下:

#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
char* ch1="abcd";
cout<<ch1<<endl;
cout<<*ch1<<endl;
}


输出结果为:



有上述实验可知,ch1存放的是文本字符串的头指针,当用*ch1输出时,相当于输出指针ch1指向的内容

继续做一个关于字符串的实验,代码如下:

#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
char ch1[]={'a','b','c'};
char ch2[]="def";
for(int i=0;i<3;i++)
{
cout<<"ch1[i]输出"<<ch1[i]<<endl;
cout<<"*ch1输出"<<*ch1<<endl;
cout<<"ch1输出"<<ch1<<endl;
}
for(int j=0;j<3;j++)
{
cout<<"ch2[i]输出"<<ch2[j]<<endl;
cout<<"*ch2输出"<<*ch2<<endl;
cout<<"ch2输出"<<ch2<<endl;
}

}


结果如下:



由此可见,数组名也是指代该字符串的首个字符的地址,而且注意文本字符串的特殊性:ch="abc"

另外又做了一个关于字符串的实验

#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
char* ch1="abc";
char* ch2="abc";
for(int i=0;i<3;i++)
{
cout<<*ch1<<endl;
ch1++;
}

for(int j=0;j<3;j++)
{
cout<<ch2<<endl;
ch2++;
}

}

实验结果为:



由此可见,当定义char* ch1为文本字符串“abc”的时候,返回的是文本字符串"abc"的首地址,当用cout输出ch1时,输出的是整个文本字符串
而当用ch1++将ch1的地址后移的时候,则此时ch1指向的是后续字符指针
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: