0

any suggestion on how to strip characters from char array pass as pointer in C++. i must use memcpy function to copy.

void foo(char *test)
{
char a[1] = {0};
char b[1] = {0};
char c[1]= {0};

memcpy(&a,&test[0],1);
memcpy(&b,&test[1],1);
memcpy(&c,&test[2],1);

cout << a <<endl;
cout << b <<endl;
cout << c <<endl;
}

int main()
{
char uibuffer[4] = "ABC";
foo(uibuffer);
return 0;
}

the current output is:

ABC��
BC��
C��

desired output is:

A
B
C
0

4 Answers 4

3
void foo(char *test)
{
/* Please note, you need to add one extra byte here for a terminator */
char a[2] = {0};
char b[2] = {0};
char c[2]= {0};

memcpy(&a,&test[0],1);
memcpy(&b,&test[1],1);
memcpy(&c,&test[2],1);

cout << a <<endl;
cout << b <<endl;
cout << c <<endl;
}

int main()
{
char uibuffer[4] = "ABC";
foo(uibuffer);
return 0;
}

OR

Think about improving your code by getting rid of arrays and memory copying. Simple char a = buffer[x] will do the trick.

Sign up to request clarification or add additional context in comments.

5 Comments

@werewindle: No, it will be a pointer to an array, which is the same thing as a pointer to the first character.
@Benjamin Lindley, pointer to array - is simply a. &a will be point to pointer to array. Wee need memcpy(a,&test[0]) or memcpy(&a[0],&test[0]) or memcpy(a,test), which is the same.
@werewindle: No. a is an array. It can decay to a pointer to char, but it is still an array. &a is a pointer to an array. Test it out. Yes, memcpy(a,&test[0],1) will work, but so will memcpy(&a,&test[0],1)
Ok, it was my fault. &a and a points to the same memory. I need to reread C specs :)
Slight correction to "which is the same thing as a pointer to the first character" -- I should have said, it's the same address as a pointer to the first character, but it's not the same thing.
2

since you haven't created \0 terminated strings do:

cout << a[0] <<endl;
cout << b[0] <<endl;
cout << c[0] <<endl;

Comments

2

Don't make a, b and c an array. Probably won't compile but to illustrate.

void foo(char *test)
{
char a = 0;
char b = 0;
char c = 0;

memcpy(&a,&test[0],1);
memcpy(&b,&test[1],1);
memcpy(&c,&test[2],1);

cout << a <<endl;
cout << b <<endl;
cout << c <<endl;
}

int main()
{
char uibuffer[4] = "ABC";
foo(uibuffer);
return 0;
}

Comments

1

Don't make them arrays:

char a = test[0];
char b = test[1];
char c = test[2];

You can still use memcpy, if you must, just as you are now.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.