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