Reputation: 3221
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.
Upvotes: 0
Views: 14049
Reputation: 3731
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.
Upvotes: 1
Reputation: 11787
strcpy
has to be used on char array not characters!!
Also look into this Que c remove the first character of an array
Upvotes: 0
Reputation: 437336
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);
Upvotes: 2
Reputation: 258568
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
?
Upvotes: 3