0

I am working with a C/C++ library that has a Python API and on the Python side I encountered this piece of code when passing a Python list to C

from ctypes import c_int, c_size_t

def cvecint(o):
    return (c_int * len(o))(*o), c_size_t(len(o))

which when called with an empty list, returns what appears to be a 0-length array

>>> cvecint([])
(<__main__.c_int_Array_0 object at 0x7f53470fa940>, c_ulong(0))

I thought 0-length arrays in C were not part of the standard, see What happens if I define a 0-size array in C/C++?. Same goes for C++, with both C arrays and std::vectors.

Am I missing something? This code is not standard compliant, does it work purely based on some compiler extension for 0-length arrays? And if so, is there a better way of passing an empty Python list to C (and possibly C++)?

gnikit
  • 1,031
  • 15
  • 25
  • 1
    The thing you can't have is an explicit `int a[0];`. Empty vectors are absolutely fine. And e.g. a pointer that points to the one-past-the-end element of an array is effectively a pointer to zero elements of that type. – Mat Aug 26 '22 at 11:58
  • I see, thanks. If we were to check the pointer in C however `if (p)...` it would be treated as `NULL` right? – gnikit Aug 26 '22 at 12:03
  • Empty *vectors* are fine, but that's C++. The OP is right that standard C does not support zero-length arrays. – John Bollinger Aug 26 '22 at 12:03
  • But that does not prevent ctypes from providing a *Python* representation of a zero-length C array. And there's good reason to think that such a thing could interoperate with C. – John Bollinger Aug 26 '22 at 12:08
  • This is a *Python* wrapper. Did you actually try to pass it to *C*? I wonder what's the purpose of this? – CristiFati Aug 26 '22 at 16:51
  • 1
    In C, you can `char* x = malloc(0);` and get a valid non-null pointer to a 0-length buffer. That's the C equivalent of the Python code. – Mark Tolonen Aug 27 '22 at 01:42
  • Re "_I thought 0-length arrays in C were not part of the standard_". That's not completely correct. It is (obviously) possible to have a 0-length array. However, **defining** an array with a fixed size of 0 is not allowed. – wovano Aug 31 '22 at 15:02

0 Answers0