字符串循环右移运行报“段错误”
各位大大,下面的程序是想完成字符串的循环右移,比如 A=“abcdefghijkl”,右移2位(steps = 2),变成 A=“klabcdefghij”。小弟写的代码在ubuntu中编译运行时,发现报段错误。不知道错在哪里,小弟学识浅薄,还请各位不要笑话小弟,烦请指点一下。谢谢!
1 #include <stdio.h> 2 #include <string.h> 3 void LoopMove(char *pStr,int Max_Len,int steps) 4 { 5 int n =Max_Len -steps; 6 char temp[Max_Len]; 7 memcpy(temp,pStr+n,steps); 8 memcpy(pStr+steps,pStr,n); 9 memcpy(pStr,temp,steps); 10 } 11 12 void main() 13 { 14 char *p="abcdefghijkmn"; 15 16 int n=0; 17 int MAX_len = strlen(p); 18 printf("Please input you want steps:\n"); 19 scanf("%d",&n); 20 21 LoopMove(p,MAX_len,n); 22 printf("the string is %s\n",p); 23 }#include<stdio.h>void f(int a){ int b[a]; printf("good\n");}int main(void){ int a=3; f(a); return 0;}
[解决办法]
#include <stdio.h>#include <stdlib.h>#include <string.h>void LoopMove(char *pStr, int Max_Len, int steps){ int n = Max_Len - steps; char *temp = (char *)malloc(sizeof(char) * Max_Len); //用了动态内存 memcpy(temp,pStr+n,steps); memcpy(pStr+steps,pStr,n); memcpy(pStr,temp,steps); free(temp);}void main(){ char p[] = "abcdefghijkmn"; int n = 0; const int MAX_len = strlen(p); printf("Please input you want steps:\n"); scanf("%d",&n); LoopMove(p,MAX_len,n); printf("the string is %s\n",p);}Please input you want steps:3the string is kmnabcdefghij请按任意键继续. . .我帮你改了下 不知道是不是你要的结果。
[解决办法]
char amessage[] = "now is the time"; /* an array */
char *pmessage = "now is the time"; /* a pointer */
amessage is an array, just big enough to hold the sequence of characters and '\0' that initializes it. Individual characters within the array may be changed but amessage will always refer to the same storage.
On the other hand, pmessage is a pointer, initialized to point to a string constant; the pointer may subsequently be modified to point elsewhere, but the result is undefined if you try to modify the string contents.
[解决办法]
我编译的时候有一个显示错误就是那个数组的大小要是确定值,我改成const int Max_Len也不行,后来就用动态数组达到一样的效果。
还有一个隐示的错误就是字符串常量是不能被修改的,要把char p[] = "abcdefghijkmn"; 改成char p[] = "abcdefghijkmn";
[解决办法]
第一个显示的错误就是当你定义局部变量数组时要确定数组的大小,所以你的那也不行,我就用动态数组达到同样的效果。
还有一个隐示错误就是字符串常量是不能被修改的,要把char *改成数组形式,数组能被修改。