首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

字符串循环右移运行报“段异常”

2012-04-07 
字符串循环右移运行报“段错误”各位大大,下面的程序是想完成字符串的循环右移,比如 A“abcdefghijkl”,右移2

字符串循环右移运行报“段错误”
各位大大,下面的程序是想完成字符串的循环右移,比如 A=“abcdefghijkl”,右移2位(steps = 2),变成 A=“klabcdefghij”。小弟写的代码在ubuntu中编译运行时,发现报段错误。不知道错在哪里,小弟学识浅薄,还请各位不要笑话小弟,烦请指点一下。谢谢!

C/C++ code
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 }


[解决办法]
char *p="abcdefghijkmn";

改成char p[]="abcdefghijkmn";
你的写法中p为字符串常量,是不能更改的
[解决办法]
char *p="abcdefghijkmn";字符串常量不可以修改的,通过看你的被调用函数你是对只读字符串进行了写操作,所以会出现段错误。修改一下,设置成字符数组。

[解决办法]
我在编译你的程序出现这个 xpected constant expression提示错误。我查了下百度,说是什么数组大小不能用变量,估计是echar temp[Max_Len];有问题。看看这个程序:
C/C++ code
#include<stdio.h>void f(int a){    int b[a];    printf("good\n");}int main(void){    int a=3;    f(a);    return 0;}
[解决办法]
探讨

char *p 不是把*p定义成指针了么?

[解决办法]
C/C++ code
#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也不行,后来就用动态数组达到一样的效果。

还有一个隐示的错误就是字符串常量是不能被修改的,要把
C/C++ code
char p[] = "abcdefghijkmn"; 改成char p[] = "abcdefghijkmn";
[解决办法]
第一个显示的错误就是当你定义局部变量数组时要确定数组的大小,所以你的那也不行,我就用动态数组达到同样的效果。
还有一个隐示错误就是字符串常量是不能被修改的,要把char *改成数组形式,数组能被修改。


探讨

帅哥,谢谢啦。其实我更想要的是错在哪里,为啥不能那样。

从你帮忙修改的代码看,你平时写代码时,比较严谨


引用:
C/C++ code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


void LoopMove(char *pStr, int Max_Len, ……

热点排行
Bad Request.