字符串与字符串常量和指针的关系

字符串常量存储在静态区域,见论坛里讨论时,有高手好像说过是存储在只读区域,不明。

字符串是存储在栈上的,属于可读可写的内存。

示例1:读写差异

#include<stdio.h>
#include<stdarg.h>

int main(){

	/*字符数组存储于动态内存中,可以进行赋值操作*/
	char message[]={'h','e','l','l',' '};
	message[2]='a';
	printf("%s
",message);
	
	/*指向字符数组的指针也可以对内存进行操作*/
	char *p=message;
	p[1]='n';
	printf("%s
",p);

	/*常量字符串存储于静态内存中,不能进行赋值操作*/
	char *p2="abcdef";
	printf("%s
",p2);//可以记性读取
	//p2[1]='n';//但是不能进行赋值操作
	printf("%s
",p2);

	return 0;
}



示例2。 猜测:一个字符串常量只有一块内存空间?所以所有指向同一字符串常量的指针,值相同?
#include<iostream>
using namespace std;
void main(void)
{
	if("join"=="join")
		cout<<"equal
";
	else cout<<"not equal
"; //equal

	char* str1="good";
	char* str2="good";
	if(str1==str2)
		cout<<"equal
";
	else cout<<"not equal
";  //equal

	char buf1[]="hello";
	char buf2[]="hello";
	if(buf1==buf2)
		cout<<"equal
";
	else cout<<"not equal
";  //not equal
	
}


最后给一个恶心的字符串题目,每次看完下次再看又忘了 (=.=)||

//指针与数组及字符串等的关系.cpp  

#include<iostream.h>

char* c[]={"You can make statement","for the topic","The sentences","How about"};
char* *p[]={c+3,c+2,c+1,c};
char***pp=p;
void main(void)
{
	
	cout<<**++pp<<endl;           //(1)The sentences

	cout<< * --* ++pp+3 <<endl;   //(2) can make statements

	cout<<*pp[-2]+3<<endl;       //(3) about

	cout<<pp[-1][-1]+3<<endl;    //(4) the topic

}


/*  
(1) **++pp等价于**(++pp),运算后pp指针指向p[1],而p[1]指针指向c[2],c[2]指向字符串“The sentences”
(2)++pp后,pp指针指向p[2],--(*(++pp))指向c[0],c[0]指向字符串“You can make statements”.pp还是指向
原来的p[2].
(3)pp[-2]等价于*(pp-2),pp[-2]指向c[3].pp还是指向p[2].
(4)pp[-1]指向c[2],pp[-1][-1]等价于*(pp[-1]-1),pp[-1]-1指向c[1],c[1]指向字符串“for the topic”

*/