-3

Write a program to reverse the strings stored in the following array of pointers to strings:

char *s[ ] = {
  "To err is human...",
  "But to really mess things up...",
  "One needs to know C!!"
};

Hint: write a function xstrrev ( string ) which should reverse the contents of one string. Call this function for reversing each string stored in s.

Why am I not getting correct output with this code?

#include "stdafx.h"
#include "conio.h"
#include "stdio.h"
#include "string.h"

using namespace System;

void xstrrev (char str[])
{
    int i,l;
    char temp;
    l=strlen(str);

    for (i=0;i<(l/2);++i)
    {
        temp=*(str+i);
        *(str+i)=*(str+i+l-1);
        *(str+i+l-1)=temp;
    }
}

void main ()
{
char *s[] = {
        "To err is human...",
        "But to really mess things up...",
        "One needs to know C!!"
    };
    xstrrev(s[0]);
    xstrrev(s[1]);
    xstrrev(s[2]);
    puts(s[0]);
    puts(s[1]);
    puts(s[2]);
    getch();
}
effeffe
  • 2,821
  • 3
  • 21
  • 44

1 Answers1

0

Are I can notice only thing you are doing wrong in declaration of s[]. You should declare you s[] in main() like this:

char str1[] = "To err is human...";
char str2[] = "But to really mess things up...";
char str3[] = "One needs to know C!!";
char *s[] = { str1, str2, str3};

Reason:

if you do like:

char* str = "yourname";
str[2] = 'c';    // you are trying to write on read only memory

you are trying to write on read only memory. that cause of segmentation fault (undefined behavior) Because str points to a constant string literal.

Where are if you do like:

char str[] = "yourname";
str[2] = 'c';    // ok no error

Then its ok because this time str[] is an array string and its value and size defined at point of declaration.

I think algorithm wise you are correct

EDIT and I am correct. see here you code is working after my suggestion Codepad and what @carlNorm said is correct. He also posted a good link.

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208