Difference between char and char[1]

后端 未结 3 1464
醉酒成梦
醉酒成梦 2020-12-24 01:37

In C++ what is the difference (if any) between using char and char[1].

examples:

struct SomeStruct
{
   char x;
   char y[1];
};

Do

3条回答
  •  温柔的废话
    2020-12-24 02:33

    As well as the notational differences in usage emphasised by Steve, char[1] can be passed to e.g. template void f(char(&a)[N]), where char x = '\0'; f(&x); wouldn't match. Reliably capturing the size of array arguments is very convenient and reassuring.

    It may also imply something different: either that the real length may be longer (as explained by dmckee), or that the content is logically an ASCIIZ string (that happens to be empty in this case), or an array of characters (that happens to have one element). If the structure was one of several related structures (e.g. a mathematical vector where the array size was a template argument, or an encoding of the layout of memory needed for some I/O operation), then it's entirely possible that some similarity with other fields where the arrays may be larger would suggest a preference for a single-character array, allowing support code to be simpler and/or more universally applicable.

提交回复
热议问题