Monday, February 21, 2011

How to correctly define char array

Hi all,

Does anyone know how should ASF_OBJECT_GUID_TEST be defined to avoid compilation error in the line marked below, or where I can find more information about it?

Thanks,

Andre

#define ASF_OBJECT_GUID_TEST {(char)0x75, (char)0xB2, (char)0x00}

void testFunction(char * testChar)
{

}

int main(int argc, char * argv[])
{
   char test[] = ASF_OBJECT_GUID_TEST;

   testFunction(test);
   testFunction(ASF_OBJECT_GUID_TEST); // <- fails to compile this line of code

   return 0;
}
From stackoverflow
  • {(char)0x75, (char)0xB2, (char)0x00}
    

    is an initializer list and is not itself an array (or a pointer) in C89.

    You instead could use:

    #define ASF_OBJECT_GUID_TEST "\x75\xB2"
    
  • you want to cast the ASF_OBJECT_GUID_TEST, i.e

    testFunction((char[])ASF_OBJECT_GUID_TEST)

    or

    #define ASF_OBJECT_GUID_TEST (char[]){(char)...}

    Alok : The `(char)` casts inside the curly braces are not needed of course (you probably know this, so the comment is mostly for the OP). Also, this is C99 only.
  • Thanks. That was exactly what I was looking for.

    Supposed I have defined many string literals which have 8 characters, and each 2 of them make actually the value of a byte. Is there a way to create a macro that would modify those string literals by adding a "\x" between every couple of characters like the following?

    #define TEST SOME_MACRO("33698149")
    

    Where TEST would be "\x33\x69\x81\x49"

    Wallacoloo : This should be asked as a new question, or you should edit your original post to include this question.
    Alok : Definitely a new question, although the short answer is "no, you can't do that".

0 comments:

Post a Comment