分段错误:
int main(){
const char *string = "This is not reverse";
char *reverse;
char temp;
int length, i = 0;
length = strlen(string);
strcpy(reverse, string);
while(i < (length/2)){
temp = *(reverse+i); // this is the reason for segmentation fault..but why?
i++;
}
}
有人可以解释相同的原因
答案 0 :(得分:4)
您需要为反向分配空间。例如
char *reverse = malloc(strlen(string) + 1);
顺便说一句,其余代码似乎有一个算法错误。我想你想做的是:
#include <string.h>
#include <malloc.h>
int main(){
const char *string = "This is not reverse";
int length = strlen(string);
char *reverse = malloc(length + 1);
int i = 0;
while(i < length){
*(reverse + i) = *(string + length - i - 1);
i++;
}
printf("%s\n", reverse);
return 0;
}
答案 1 :(得分:-1)
而不是strcpy(reverse, string);
使用reverse = string
,因为您不需要为反向分配空间,只需指向反向字符串即reverse = string