运行以下代码后出现段错误:
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++;
}
}
谁能解释一下原因
最佳答案
您需要为reverse 分配空间。例如
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;
}
关于c - 访问 char 字符串时无法理解段错误的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19886967/