I am trying to reverse a string in-place using two pointers to the same string. First one(char *p
) points to the starting location of the string and second one(char *q
) points to the ending location of the string. So when I tried to debug using gdb, I get am getting segmentation fault at line 16.
When I tried to print the values of *p
and *q
, it works fine. Why am I getting segfault while I'm still able to access those location?
Breakpoint 1, main () at reverse.c:16
16 *q = *p;
(gdb) print p
$1 = 0x5555555547e4 "hello"
(gdb) print q
$2 = 0x5555555547e8 "o"
(gdb) step
Program received signal SIGSEGV, Segmentation fault.
0x00005555555546db in main () at reverse.c:16
16 *q = *p;
The actual code of the program is
#include<stdio.h>
int main() {
char *array = "hello";
char *p=&array[0];// pointer to the first element
// Make q point to last value of the array
char *q = &array[0];
while(*q) q++;
char temp;
q--; // move left so that we don't point to `\0`
while(p<q){
temp = *p;
*q = *p;
*p = temp;
p++;q--;
}
printf(" Done reversing \n");
}