tags:

views:

130

answers:

2

Hi all,

Can someone explain why the following error happens:

    #define bla "\xA"
    char a [2] = {0};
    memcpy (a,bla,1); // a[0] = 0x0a <- Correct
    //a[1] = bla;     // '=' : cannot convert from 'const char [2]' to 'char'

Thanks,

RM

+5  A: 

The types are different: a[1] is a char and "\xA" is an array of char.

In C++ and C anything enclosed in double quotes (including nothing) is an array of char.

anon
Yes but should char[1] assigned to char work ?and why is it a char [2] array ?
Roman M
You're declaring a string which implicitly has a terminating zero character (U+0000) at the end, so "x" is two characters: x and \0
Joey
I thought \xA is treated as single byte i.e bla should be a single byte (char) array ? I thought \xA is treated a single byte i.e bla should be a single byte (char) array ? – Roman M 0 secs ago [delete this comment]
Roman M
Don't forget that all strings are terminated with \0, so even if you assign a single char in the string its still two.
Shay Erlichmen
\xA is a single byte, but since you put it in double quotes and not single quotes, it is treated as a string (not a character) and so has an implicit nul byte after it to terminate the string.
Tyler McHenry
This answers the question correctly.
EvilTeach
+4  A: 

Try:

#define bla '\xA'

Although that will stop the memcpy working.

Daniel Earwicker
Bingo.So if I use " " it treats it creates a null terminated array of charand if I user ' ' it just treats it like a char right ?
Roman M
@Roman Yes - but note this has nothing to do with #define
anon
`memset()` will work, however.
Tim Sylvester