How to create empty char arrays in Cython without loops

Well it seems easy, but I can't find any links on the internet. In C, we can create an array of char

null characters n

like this:

char arr[n] = "";

      

But when I try to do the same in Cython with

cdef char arr[n] = ""

      

I am getting this compilation error:

Error compiling Cython file:
------------------------------------------------------------
...
cdef char a[n] = ""
                   ^
------------------------------------------------------------

Syntax error in C variable declaration

      

Obviously Cython doesn't allow you to declare arrays this way, but is there an alternative? I don't want to manually set each element in the array, that is, I am not looking for something like this

cdef char a[10]
for i in range(0, 10, 1):
    a[i] = b"\0"

      

+3


source to share


3 answers


You don't need to set every element to create a null string. Simply zeroing the first element is enough:

cdef char arr[n]
arr[0] = 0

      

Next, if you want to zero out the entire char array, use memset

from libc.string cimport memset
cdef char arr[n]
memset(arr, 0, n)

      

And if the C purists are complaining about 0 instead of '\ 0', note that '\ 0' is a Python (unicode in Python 3) string in Cython. '\ 0' is not a C char in Keaton! memset expects an integer value for its second argument, not a Python string.

If you really want to know the value of int C '\ 0' in Cython, you should write a helper function in C:



/* zerochar.h */
static int zerochar() 
{
    return '\0';
}

      

And now:

cdef extern from "zerochar.h":
    int zerochar()

cdef char arr[n]
arr[0] = zerochar()

      

or

cdef extern from "zerochar.h":
    int zerochar()

from libc.string cimport memset
cdef char arr[n]
memset(arr, zerochar(), n)

      

+2


source


In C, 'is used for char and "for string. But any" empty char "doesn't really make sense, you probably want" \ 0 "or just 0

May be:

import cython
from libc.stdlib cimport malloc, free

cdef char * test():
    n = 10
    cdef char *arr = <char *>malloc(n * sizeof(char))

    for n in range(n):
        arr[n] = '\0'

    return arr

      



Edit

void *
 calloc(size_t count, size_t size);

      

This is for you,

+1


source


What about:

cdef char *arr = ['\0']*n

      

0


source







All Articles