i am trying to create a string function which is callable from the main function, however this gives segmentation fault… any ideas???
also is it possible to create a string function which returns a string..
#include <iostream>
#include <stdio.h>
#include <sstream>
using namespace std;
string callMe(string& k){
cout << "String from callMe: " << k;
}
int main(){
string k;
k = "K SHK";
cout << "String from main function: " << k << endl;
callMe(k);
}
UPDATE:
its compiles fine..
[root@server dev]# ./stringtest
String from main function: K SHK
Segmentation fault
The problem is that you have declared your function as returning a
string, but don’t return one.There are two ways to fix it:
If you didn’t intend to return a string, change
callMetovoid callMe(string& k);If you did intend to return a string, then do so, by adding a return statement, e.g.
return "I'm returned from callMe, called with " + k;Additionally, some style comments:
It is a good idea to initialize variables right at the point of definitions where possible. In your case you’d write:
or
If you don’t intend to modify the string afterwards, you might also consider to define is as
constto catch accidental changes (e.g. by use of=instead of==):If you don’t change the argument in
callMe, you should use a reference to const:resp.
This will allow you to call the function on constant strings and string literals, like
callme("I'm a string literal");