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

Recommended Answers

All 2 Replies

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.]

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$ 
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.