0

I am unable to locate the cause of the segmentation fault objective-to reverse a string using pointers

#include<stdio.h>
#include<string.h>

void swap(char *ptr[], int c)
{
  int i;
  char  *r[40];    
  for(i=0; i<c; i++)
    *(r[c-i]) = *(ptr[i]);
  printf("%s",*r);
}

main()
{
  int i;
  char *ptr[20],str[40];

  printf("enter string:");
  gets(str);
  for(i=0; i<(strlen(str)); i++)
    ptr[i]=&(str[i]);
  swap(ptr,strlen(str));    
}
Jens
  • 69,818
  • 15
  • 125
  • 179
raven
  • 3
  • 1
  • 2
    I don't know why you are using an array of string pointers, but even so, `r[c-i]` should be `r[c-i-1]` if `c` is the array length. And then, you make the classic "howler" of swapping the characters *twice* instead of of stopping in the middle. – Weather Vane Apr 20 '16 at 17:25
  • 1
    Possible duplicate of [Definitive List of Common Reasons for Segmentation Faults](http://stackoverflow.com/questions/33047452/definitive-list-of-common-reasons-for-segmentation-faults) – CodeMouse92 Apr 21 '16 at 20:07

1 Answers1

3

Problem lies here -

char  *r[40];    
for(i=0;i<c;i++)
  *(r[c-i])=*(ptr[i]);

Here you declare array of char pointers r and you dereference these uninitialized pointers which must have caused seg fault .

ameyCU
  • 16,489
  • 2
  • 26
  • 41