Ok so here are the parts of my code that I'm having trouble with:
char * historyArray;
historyArray = new char [20];
//get input
cin.getline(readBuffer, 512);
cout << readBuffer <<endl;
//save to history
for(int i = 20; i > 0; i--){
strcpy(historyArray[i], historyArray[i-1]); //ERROR HERE//
}
strcpy(historyArray[0], readBuffer); //and here but it's the same error//
The error that i'm receiving is:
"invalid conversion from 'char' to 'char*'
initializing argument 1 of 'char* strcpy(char*, const char*)'
The project is to create a psudo OS Shell that will catch and handle interrupts as well as run basic unix commands. The issue that I'm having is that I must store the past 20 commands into a character array that is dynamically allocated on the stack. (And also de-allocated)
When I just use a 2d character array the above code works fine:
char historyArray[20][];
but the problem is that it's not dynamic...
And yes I do know that strcpy is supposed to be used to copy strings.
Any help would be greatly appreciated!
historyArray[i] is a char. It is a single character. You want to use a sting. Your fundemental problem is that historyArray is a
char*
which means that it points to a memory range containing characters. You want it to be achar**
which is a pointer to a pointer to a string. Your initialization code would behistoryArray
points to (the first element of) an array of 20char
s. You can only store one string in that array.In C, you could create a
char**
object and have it point to the first element of an array ofchar*
objects, where each element points to a string. This is what theargv
argument tomain()
does.But since you're using C++, it makes a lot more sense to use a
vector
ofstring
s and let the library do the memory management for you.But that will only fix the compiler errors, not the logical errors in the code. Your using C++ so the string solution:
Alternatively if you want one long string containing everything from readBuffer:
For example...
Error 1: You're indexing past your array bounds with i being set to 20.
Error 2: historyArray[i] is a char, not a char *. You need &historyArray[i].
Two solutions. The first is if you for some reason really want arrays, the other is more recommended and more "C++"ish using
std::string
s.Then you can use
strcpy
on the elements inhistoryArray
.Second solution which I repeat is recommended (I've fixed a few other things):
Array notation gives references while strcopy wants pointers. Convert references to pointers with address-of (&) operator.