Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid conversion from 'char' to 'char*' using strcpy

Tags:

c++

char

strcpy

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!

like image 412
OmegaTwig Avatar asked Jan 18 '26 20:01

OmegaTwig


1 Answers

historyArray points to (the first element of) an array of 20 chars. 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 of char* objects, where each element points to a string. This is what the argv argument to main() does.

But since you're using C++, it makes a lot more sense to use a vector of strings and let the library do the memory management for you.

like image 185
Keith Thompson Avatar answered Jan 20 '26 11:01

Keith Thompson