-
Anyone can help me?
The code's function is decribed as follow,but it doesn't work.The problem must be caused by the line "strcpy(pStr,temp);//This line caused the problem,so why?"
--but i don't know why.Any suggestion will be helpful,thanks advanced.
Code:
//This function loop shift the string right by nsteps,for example,if "1234" input,the output will be "3421"
#include <string.h>
#include <iostream.h>
#define MAX_LEN 20
int LoopMove(char *pStr,int nSteps);
int main()
{
char *pStr = "0123";
int nSteps = 2;
LoopMove(pStr,nSteps);
return 0;
}
int LoopMove(char *pStr,int nSteps)
{
char temp[MAX_LEN];
int n;
n = strlen(pStr) - nSteps;
strcpy(temp,pStr + n);
strcpy(temp + nSteps,pStr);
*( temp + strlen(pStr) )= '\0';
strcpy(pStr,temp);//This line caused the problem,so why?
cout<<pStr<<endl;
cout<<temp<<endl;
cout<<strlen(pStr)<<" equal to "<<strlen(temp)<<endl;
return 0;
}
-
When you define
Code:
char *pStr = "0123";
I suspect the compiler has put the string into a protected part of memory. You are trying to write over it in your function.
Todd
-
> #include <string.h>
> #include <iostream.h>
The first thing to decide is whether you're a C programmer or a C++ programmer.
To fix the "string is a const" problem, go with
char pStr[] = "0123";
Then call your function.
-
Thanks for you two guys' advice.
aha,i use VC++ 6.0 to edit and compile the source code,so i choose "cout" to print something instead of "printf" just for convenience.
after your advice,i have resolved the problem.But can you explaint if for me?
I declare:
char *pStr = "1234";//here,it is not a " const char *pStr = "1234" ",why i can't use the strcpy() to rewrite it?
thanks
-
Hi,Salem
what does your profile mean?
are you suggesting to use int main rather than void main?
-
A "string constant" can be placed in read-only memory even if you don't use the word "const" in the declaration. It's the only exception to the rule to stop a hell of a lot of existing code which is otherwise fine from being broken. Expect the exception to go in a future standard.
Being read-only, any attempt to modify it results in the OS instantly killing off the program.
-
> are you suggesting to use int main rather than void main?
It's not a suggestion.
-