Reputation: 823
I'm working with a piece of C++ code that reads lines from a txt
file and then assign each line to to an array
called lines
. Then it calls a function that converts each element in the lines
array to a char array
and then return the resulted char array
. This step is where I stuck. How could I return a char array
from the function toChar
and assign the returned array to another array
so I can use it as I need? (the rest of the code should use each returned char array
to write it in a pipe, this not important right now but just to clarify why I need to learn to return an array from a function)
Here is the code I'm using:
#include <fstream>
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <cstdlib>
using namespace std;
char * toChar(string line);
int main()
{
string lines[0] = "line1";
char* a = toChar(lines[0]);
return 0;
}
char * toChar(string line)
{
char a[1024];
strcpy(a, line.c_str());
return a;
}
Please note that in this code I'm trying to shrink the code so I'm assigning a simple string
value to the array
when I try to compile this code, the error below appears:
warning: address of local variable 'a' returned
any help or suggestion is greatly appreciated..
Upvotes: 0
Views: 2763
Reputation: 3145
First use a const &
in passing the string to the function to avoid the unnecessary copying, and be able to use temporaries, e.g. toChar("I am temp");
The are the following alternatives:
(1) Return std::string
std::string toChar(std::string const & line)
{
char a[1024];
strcpy(a, line.c_str());
return a;
}
Of course it is assumed that line
is smaller than 1024 chars with the null termination symbol
(2) Return an allocated array the
char * toChar(std::string const & line)
{
char * a = new char[1024];
strcpy(a, line.c_str());
return a;
}
but you will have to actually manage it and delete it later.
(3) Allocate the array and pass it to the function
void toChar(string const & line, char a[])
{
strcpy(a, line.c_str());
}
I imagine that you actually want to extract a C-string from an std::string , or some part of it. The proper way to do it is (3).
Upvotes: 3
Reputation: 1775
If you want to access to the internal storage of your string you can call line.c_str()
which returns a const char *
.
Hence you won't need you function toChar
that creates a local array that will go out of scope at the end of your function.
You could simply do :
int main()
{
string lines[0] = "line1";
const char* a = lines[0].c_str();
return 0;
}
But I advise you to keep manipulating std::string
as they will handle string better than a simple char *
.
And if you want a copy, just do it : std::string mycopy = lines[0]
.
Upvotes: 1
Reputation: 12445
The warning is correct and practically is an error. You're declaring the char array locally so it will be deleted after going out of scope of that function and its address will be no more valid.
Since you're using c++ avoid char array and use a std::string
.
Upvotes: 1