char* f(){
      char* result;//I have to return 'result' at the end of this function, where result should be containing i (i.e. int i=97) in it.

      int i = 97;

      //Do whatever you can

      return result;
}

Dani AI

Generated

Your question can mean two very different things, so first a clarification (this is where most confusion comes from in the thread): do you want the textual decimal digits for the integer (the string "97"), or do you want a pointer to the binary bytes that hold the int in memory (four bytes on most systems)? The safe, modern C++ answers differ.

For the textual form (recommended): return a std::string and let the caller take a pointer if needed. This avoids lifetime bugs with temporary buffers.

#include <string>

std::string f() {
    int i = 97;
    return std::to_string(i);   // "97"
}

// caller:
auto s = f();
const char* p = s.c_str();     // valid while s lives

If you must return an owning, modifiable C-style buffer, return a smart pointer so ownership is clear (caller keeps the unique_ptr). This avoids naked new/delete errors.

#include <charconv>
#include <memory>

std::unique_ptr<char[]> f_owned() {
    int i = 97;
    auto buf = std::make_unique<char[]>(12);
    auto res = std::to_chars(buf.get(), buf.get()+12, i);
    *res.ptr = '\0';
    return buf;   // caller keeps the unique_ptr
}

For raw binary (not textual) — e.g. serialization — copy the bytes of the int into a container and return that; don’t return a pointer to a stack variable.

Troubleshooting notes tied to earlier posts: was right that *p is a single char (so cout << *p prints the first character); use cout << p to print the whole C-string. ’s intent to use streams is fine, but stringstream str(i) is not a standard constructor (that caused ’s compiler error). Also beware: std::string::c_str() returns a pointer that becomes invalid as soon as the string is destroyed — do not return s.c_str() from a function where s is local.

Recommended Answers

All 10 Replies

What's the purpose of that function, why do you need to convert the int to a string? In c++ you can use stringstream to make the conversion

#include <string>
#include <sstream>
using namespace std;

std::string foo()
{
   int i = 20;
   string n;
   stringstream str(i);
   str >> n;
   return n;
}

Thanks but I need a char* being returned not a string.

You can get the char* from the string after it's returned.

char* s = string.c_str()

The only other option is to allocate new memory, then you have to make sure to delete it when no longer needed.

#include <cstdlib>

char* foo()
{
   int i = 20;
   char* n = new char[8];
   sprintf(n,"%d",i);
   return n;
}

int main()
{
    char* n = foo();
    delete[] n; // deallocate memory when done with it
}
    int n = 97;
    string str = "192327";
    const   char *p = str.c_str();
    cout << *p << endl;

Output: 1
Why so? I wan't whole p to point to whole str.

cout << *p << endl;

What is *p ? It is a single char, so you get a single char output. If you want to output the whole thing, use cout with the char pointer: cout << p;

#include <iostream>
#include <sstream>
using namespace std;

int main(){
        int i = 97;
        string n;
        stringstream str(i);
        str >> n;
//      const char* s = n.c_str();
//      cout << s << endl;
        return 0;
}

Gives Errors in my g++:

//g++ 2.cpp -o 2.out//Command to compile

2.cpp: In function ‘int main()’:
2.cpp:8:20: error: invalid conversion from ‘int’ to ‘std::ios_base::openmode {aka std::_Ios_Openmode}’ [-fpermissive]
In file included from 2.cpp:2:0:
/usr/include/c++/4.7/sstream:518:7: error: initializing argument 1 of ‘std::basic_stringstream<_CharT, _Traits, _Alloc>::basic_stringstream(std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::ios_base::openmode = std::_Ios_Openmode]’ [-fpermissive]

There is no stringstream constructor that takes a single parameter of type int. This function:
stringstream str(i);
does not exist.

You are right. The code I posted should have been like below. It compiles as previously stated with Visual Studio 2012 but produces undefined behavior.

int main()
{
   int i = 1024;
   string n;
   stringstream str;
   str << i;
   str >> n;
   cout << n << '\n';


}

Oh, really? That's interesing. I had a quick poke around their documentation at the constructors they list, which I think is here:

http://msdn.microsoft.com/en-us/library/93sye325.aspx

There isn't an obvious one that would work; maybe the VS compiler is happy to cast that int into a string. When you build that in VS2012, what are the contents of the stringstream?

I suspect VS is typcasting the int to char

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.