char [] 和 char *区别:
1. char[] p :表示p是一个数组指针,相当于const pointer,不允许对该指针进行修改。但该指针所指向的数组内容,是分配在栈上面的,是可以修改的。
2. char * pp: 表示pp是一个可变指针,允许对其进行修改,即可以指向其他地方,如pp = p也是可以的。
对于char *pp = "abc";将 abc\0 存放在常量区域内,不能修改。然后pp指针是局部变量,存放在栈中,因此,在函数返回中,允许返回该地址(实际上指向一个常量地址,字符串常量区);而char[] p是局部变量,当函数结束,存在栈中的数组内容均被销毁,因此返回p地址是不允许的。
也就说明为什么不能用sort函数对char * 字符串排序,无法变动字符位置!
p = pp ; //error
pp = p;//success
int a=0; //全局初始化区
char *p1; //全局未初始化区
main()
{
int b;栈
char s[]="abc"; //栈
char *p2; //栈
char *p3="123456"; //<span style="color:#ff0000;">123456\0</span>在常量区,p3在栈上,不能通过p3修改123456
static int c=0; //全局(静态)初始化区
p1 = (char*)malloc(10);
p2 = (char*)malloc(20); //分配得来得10和20字节的区域就在堆区。
strcpy(p1,"123456"); //123456\0放在常量区,编译器可能会将它与p3所向"123456"优化成一个地方。
}
确定一个字符串的所有字符是否全都不相同:
#include<cstring>
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
int allDiff1(char *str){
map<char,int> m;
while(*str)
m[*str++]++;
for(int i = 0 ; i < m.size(); i++)
if(m[i]>1)
return 0 ;
return 1;
}
int allDiff(char str[], int n){ //sort函数不能使用char *
sort(str,str+n);
for(int i = 0 ; i < n-1; i++)
if(str[i]==str[i+1])
return 0;
return 1;
}
int main(){
char str[] = "xyxsagfd";
if(allDiff(str, 8))
cout<<"all different"<<endl;
else
cout<<"not all different"<<endl;
}