访问char字符串时无法理解分段错误的原因

时间:2013-11-10 06:32:13

标签: c segmentation-fault strcpy

运行以下代码后

分段错误:

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

}

有人可以解释相同的原因

2 个答案:

答案 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