0

I'm having trouble removing the first two characters from my char array.

 input[MAXSIZE] = "./hello";

 for(int i = 2; i < MAXSIZE; i+=2)
 {
    strcpy(input[i-2],input[i]);
 }

and I'm getting the following errors:

 invalid conversion from ‘char’ to ‘char*’
 initializing argument 1 of ‘char* strcpy(char*, const char*)’
 invalid conversion from ‘char’ to ‘const char*’
 initializing argument 2 of ‘char* strcpy(char*, const char*)’

I know that this is a very basic problem but im fairly new to this. Also if there is an easier way to get around this problem feel free to educate me.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Daniel Del Core
  • 3,071
  • 13
  • 38
  • 52
  • 2
    Is there a reason you are not using `std::string`? – hmjd May 15 '12 at 10:01
  • 2
    you also may simply use a pointer to the third character (char* modified_input= &input[2]) as a new "array" without moving or copying characters at all. – user396672 May 15 '12 at 10:30

4 Answers4

3

strcpy copies null terminated char arrays, not characters.

What you want is:

input[i-2] = input[i];

Also, why don't you increment i with 1 but with 2?

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
2

As others have said, strcpy is not meant to be used like that and you can achieve the desired effect with

// loop step changed to 1; i += 2 is a mistake
for(int i = 2; i < MAXSIZE; ++i)
{
    input[i-2] = input[i];
}

However, you can also simply use memmove:

memmove(input, input + 2, (MAXSIZE - 2) / sizeof(input[0]));

If input is guaranteed to be an array of char you can also remove the / sizeof(input[0]) part.

And of course even better would be to do it the standard library way, using std::copy_backward (necessary because the source and destination ranges overlap):

#include <algorithm>
std::copy_backward(input + 2, input + MAXSIZE, input + MAXSIZE - 2);
Jon
  • 428,835
  • 81
  • 738
  • 806
1

As an alternative solution you can simply use a pointer to char to "skip" the first two characters in the array:

char input[MAXSIZE] = {0};
snprintf_s<MAXSIZE>(input, _TRUNCATE, "./hello" ); //MSVC only
char* noDotSlash = input + 2;
cout << noDotSlash << endl; //should print just hello.
Dennis
  • 3,683
  • 1
  • 21
  • 43
0

strcpy has to be used on char array not characters!!

Also look into this Que c remove the first character of an array

Community
  • 1
  • 1
Rohit Vipin Mathews
  • 11,629
  • 15
  • 57
  • 112