invalid conversion from 'char' to 'cha

2019-07-23 16:38发布

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!

标签: c++ char strcpy
7条回答
够拽才男人
2楼-- · 2019-07-23 17:26

Stop using C idioms in a C++ program:

std::deque<std::string> historyArray;

//get input
std::string readBuffer;
std::getline(std::cin, readBuffer);       
std::cout << readBuffer << std::endl;

//save to history
historyArray.push_front(readBuffer);
if(historyArray.size() > 20)
  historyArray.pop_back();

As a result, we have:

  • No buffer-overflow threat in readBuffer / getline()
  • No pointers, anywhere, to confuse us.
  • No arrays to overstep the ends of
  • Arbitrarily long input strings
  • Trivially-proven memory allocation semantics
查看更多
登录 后发表回答