oh excuse me for calling it wrong. But i hope i could tell what i want to do. I want to print this function that returns a char pointer and also i want to change the returning value of that function, writing Function1()[1]=’a’;
Now i can print the function which returns char pointer. The code is below. HOwever changing return value code doesn't work. I learn it from the tutorial site , but why doesnt it work?
#include <iostream>
#include <string.h>
#include <sstream>
char *function1()
{ return"Some text";}
usingnamespace std;
int main()
{
std::stringstream ss;
ss << function1();
string s2 = ss.str();
//function1()[1]="a"; // not working
std::cout << s2 <<std::endl;
return 0;
}
error is :
test100.cpp:18:2: error: stray ‘\342’ in program
test100.cpp:18:2: error: stray ‘\200’ in program
test100.cpp:18:2: error: stray ‘\231’ in program
test100.cpp:18:2: error: stray ‘\342’ in program
test100.cpp:18:2: error: stray ‘\200’ in program
test100.cpp:18:2: error: stray ‘\231’ in program
This is not java, actually I don't know what you are talking about. I suggest you to use strcpy() function and copy the const char* pointer return by the function to a char* and then change the value that you want.
If you want just to print what the function returns, you can make it return a const char*, which is a C-string, which means that at the end of the string there's a '\0' character.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
constchar* getConstCharPtr()
{
return"Hello World";
}
constchar* a = getConstCharPtr();
int a_length = strlen(a);//calculates the length of the string
//strlen() defined in <cstring>
char* b = newchar[a_length + 1];
strcpy(b, a);//defined in <cstring>
b[3] = 'K';
std::cout << a <<'\n';//printing a const char* normally: using <<
std::cout << b <<'\n';
You don't need the stringstream class to print a const char*!
However , i'm studying const topic and it is explained that why we should make the return value of a function "const". The sole purpose of making return value of a function const is that it prevents any change of return value of function. I understood so far. What i actually wonder that how is it possible? We are so frustrated a change of return value of function, so we define the return value const.
Suppose that the return value of the function is not const. It technically means that the return value can be changed. Then how can we change it?
Yes this perfectly is what i want. The only main difference of your code and mine is "static". Actually, deleting static from the code breaks the code and causes segmentation faults. I should learn about "static".
Thanks for your help , zwilu and long double main .