raven
raven

Reputation: 3

location of segmentation fault

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

Upvotes: 0

Views: 67

Answers (1)

ameyCU
ameyCU

Reputation: 16607

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 .

Upvotes: 3

Related Questions