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,438
  • 68
  • 55
  • 126
Daniel Del Core
  • 2,783
  • 13
  • 36
  • 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
  • 245,575
  • 61
  • 446
  • 609
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
  • 413,451
  • 75
  • 717
  • 787
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,633
  • 20
  • 42
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,207
  • 15
  • 55
  • 107