关于字符指针

C++语言 码拜 8年前 (2016-04-06) 934次浏览
#include <iostream>
using namespace std;
void jiami(char *a,int [],int);
void jiemi(char *b,int [],int);
int main()
{
char *secret = “the result of 3 and 2 is not 8”;        //不能是char *secret = “the result of 3 and 2 is not 8”;
int num[]={4,9,6,2,8,7,3};
cout<<“加密前:”<<endl<<secret<<endl;
//cout<<secret[29]<<endl;
jiami2(secret,num,7);
//cout<<“加密后:\n”<<secret<<endl;
//jiemi(secret,num,7);
//cout<<“解密后:\n”<<secret<<endl;
return 0;
}
void jiami(char *a,int n[],int m)
{
if(a==NULL) return;
else
{
int i=0;
while((*a)!=”\0″)
{
*a=char(*a + n[i%m]);
if((*a)>122) *a=((*a)-122)%90+31;
a++;
i++;
}
a=a-i;
}
}
void jiemi(char *a,int n[],int m)
{
if(a==NULL) return;
else
{
int i=0;
while(*a!=”\0”)
{
*a-=n[i%m];
if(*a<32) *a=(123-(32-*a)%90);
a++;
i++;
}
a=a-i;
}
}
为什么一运行  void jiami(char *a,int n[],int m),void jiemi(char *a,int n[],int m)函数程序就崩掉了。
解决方案

10

char *secret = “the result of 3 and 2 is not 8”;  // secret 是个指针,指向常量区的字符串”the …”,这个字符串不能修改,一改就崩
char secret[] = “the result of 3 and 2 is not 8”; // secret是局部变量,编译器会在栈上分配空间,然后把字符串拷贝到这个空间,允许修改

10

引用:

是不是说,它的问题是常量不允许修改。 那改了的话,是改变了什么?为什么会崩掉?

http://blog.csdn.net/jiaobuchong/article/details/44885789

5

引用:

char *secret = “the result of 3 and 2 is not 8”;  // secret 是个指针,指向常量区的字符串”the …”,这个字符串不能修改,一改就崩
char secret[] = “the result of 3 and 2 is not 8”; // secret是局部变量,编译器会在栈上分配空间,然后把字符串拷贝到这个空间,允许修改

是的,修改常量区数据导致的。可以将常量修改成数组,例如: char  secret[100] = {“the result of 3 and 2 is not 8”};

10

char *secret = “the result of 3 and 2 is not 8”;  表示secret 指向常量区的常量字符串 “the result of 3 and 2 is not 8”
这个区域一般是禁止进行写操作的,你尝试写入就产生异常崩溃了。
要改成是堆或栈上申请的数组才行。

1

#pragma comment(linker,"/SECTION:.rdata,RW")
//加这句可以让常量区可写,后果自负!

5

char *secret = “the result of 3 and 2 is not 8”; secret指针指向常量字符串,不能修改字符串的内容,直接用字符串数组吧!

4

字符串常量是禁止修改的。

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明关于字符指针
喜欢 (0)
[1034331897@qq.com]
分享 (0)