1

运行以下代码后出现分段错误:

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++;
    }

}

有人可以解释一下原因吗

4

2 回答 2

4

您需要为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;
}
于 2013-11-10T06:35:51.563 回答
-1

而不是 strcpy(reverse, string);use reverse = string,因为不需要为 reverse 分配空间,只需将 reverse 指向字符串即reverse = string

于 2013-11-10T06:43:30.137 回答