Hi folks

I am new to C++

i tried to reverse the characters in an array

#include <iostream>
using namespace std;

int main()
{
char kavi[]={'s','w','o','r','d','\0'};

cout<<kavi<<endl;

cout<<"now reversing the word"<<endl;

int i;
while(kavi[i] != '\0')
{
i++;
}

cout<<"Length is"<<i;

int j;
for(j=10;j>=0;j--)
{
cout<<kavi[i];
}
}

but it gave me a "segmentation fault" error.. can u pls help me and tell me as to where I am going wrong ?

thanks
kb

for(j=10;j>=0;j--)
{
cout<<kavi;
}

Do you expect your array to be size 10 always?

This works, try to see why:

char kavi[]={"my shiny sword"};

cout<<kavi<<endl;

cout<<"now reversing the word"<<endl;

int i=-1;
while(kavi[++i] != '\0');
i--;
cout<<"Length is "<<i<<endl;

for(int j=i; j>=0;j--)
    cout<<kavi[j];

The reason your code seg faults is because you have not initialized the variable "i" before using it in your while loop. If you don't initialize your variables correctly they will have random values.

You're misusing while loops, use a for loop instead. And use strlen(szString) to calculate the length of a null terminated c style string.
ie:

char const * kavi("my shiny sword");
 cout<<kavi<<endl; 
cout<<"now reversing the word"<<endl;
cout<<"Length is "<<strlen(kavi) <<endl;
 for(int j=strlen(kavi); j>=0;j--) 
   cout<<kavi[j];

Strlen will return an int of the number of letters in the string, up to but NOT including the null terminator.

This article has been dead for over six months. Start a new discussion instead.