segmentation fault after running the following code:

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

}

could someone please explain the reason for the same

有帮助吗?

解决方案

You need to allocate space for reverse. For example

char *reverse = malloc(strlen(string) + 1);

By the way, the rest of the code seems to have an algorithmic bug. I think what you wanted to do was something like:

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

其他提示

instead of strcpy(reverse, string); use reverse = string, Because you don't need to allocate space for reverse, Just point reverse to string i.e reverse = string

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top