I got run-time error in the following simple code, but I don't know what's the problem. can any one help?

#include "stdafx.h"
#include<iostream>
using namespace std;

void reverse (char * source)
{
int i=0, j=strlen(source)-1;
while (i<j)
{char temp=source[j];
source[j]=source[i];
source[i]=temp;
i++;
j--;
}
cout<<source<<endl;
}

void main()
{
reverse("university");
}

Your problem is a combination of reverse and the way you call reverse.

You have reverse (char*), as taking a char pointer. That is an area of memory that can be modified. However, when you call it, you pass a constant string. C++ represent that memory as non-mutable, i.e. It does not allow you to modify it. Hence you get a runtime error.

So to fix your problem call reverse this way

int main()
{
   char word[]="university";
   reverse(word);
   // NOTE: word has changed.
   std::cout<<"Word is now ::"<<word<<std::endl;
   return 0;
}

Additionally, main() is actually returns an int, most compilers that were written in this century, will not allow you to compile it as a void. [Which tell us that you really should get a new compiler. There are many good free compilers and IDE (Integrated development environments), available.]

Edited 6 Years Ago by StuXYZ: n/a

some minor changes and its working now.

#include<iostream>
#include<string.h>
using namespace std;

void reverse (char * source)
{
int i=0, j=strlen(source)-1;
while (i<j)
{char temp=source[j];
source[j]=source[i];
source[i]=temp;
i++;
j--;
}
cout<<source<<endl;
}

int main()
{
char c[]= "university";
reverse(c);
}



joe@localhost:~/Desktop$ g++ cc.cc
cc.cc: In function ‘void reverse(char*)’:
cc.cc:6: error: ‘strlen’ was not declared in this scope
cc.cc: At global scope:
cc.cc:17: error: ‘::main’ must return ‘int’
cc.cc: In function ‘int main()’:
cc.cc:19: warning: deprecated conversion from string constant to ‘char*’
joe@localhost:~/Desktop$ gedit cc.cc &
[1] 3351
joe@localhost:~/Desktop$ g++ cc.cc
cc.cc: In function ‘int main()’:
cc.cc:20: warning: deprecated conversion from string constant to ‘char*’
joe@localhost:~/Desktop$ g++ cc.cc
cc.cc: In function ‘int main()’:
cc.cc:20: error: expected unqualified-id before ‘[’ token
cc.cc:21: error: ‘c’ was not declared in this scope
joe@localhost:~/Desktop$ g++ cc.cc
joe@localhost:~/Desktop$ ./a.out
ytisrevinu
joe@localhost:~/Desktop$ 

Edited 3 Years Ago by Nick Evan: Fixed formatting

This question has already been answered. Start a new discussion instead.