[Pyrex] Dynamic arrays in Pyrex

Simon Frost sdfrost at ucsd.edu
Wed Jun 4 20:57:22 CEST 2003


Dear Francesc, and the Pyrex list,

I'm still trying to work with dynamic arrays. This doesn't seem to work; 
any ideas?

cdef extern from "stdlib.h":
   void *malloc(size_t size)
   void free(void *ptr)

def primes(int kmax):
   cdef int n, k, i
   cdef int *p
   p = <int *>malloc(kmax * sizeof(int))
   result = []
   k = 0
   n = 2
   while k < kmax:
     i = 0
     while i < k and n % p[i] <> 0:
       i = i + 1
     if i == k:
       p[k] = n
       k = k + 1
       result.append(n)
     n = n + 1
   free(<char *>p)
   p = NULL
   return result



At 08:18 PM 6/4/2003 +0200, you wrote:
>Hi,
>
>This should do the job:
>
>cdef extern from "stdlib.h":
>   void *malloc(size_t size)
>   void free(void *ptr)
>
>def primes(int kmax):
>   cdef int *p
>
>   p = <int *>malloc(kmax * sizeof(int))
>
> From now on, you can use p as a C array of integers
>
>Cheers,
>
>
>A Dimecres 04 Juny 2003 19:55, Simon Frost va escriure:
> > Dear Pyrex List,
> >
> > A quick (probably stupid) question as I'm a newbie. Can anyone let me know
> > the syntax for allocating and setting a dynamically sized array? Take, for
> > example, the primes example packaged with Pyrex:
> >
> > def primes(int kmax):
> > cdef int n, k, i
> > cdef int p[1000]
> > result = []
> > if kmax > 1000:
> > kmax = 1000
> > k = 0
> > n = 2
> > while k < kmax:
> > i = 0
> > while i < k and n % p[i] <> 0:
> > i = i + 1
> > if i == k:
> > p[k] = n
> > k = k + 1
> > result.append(n)
> > n = n + 1
> > return result
> >
> > If I want to set the size of p at run-time, what modifications are needed.
> >
> > TIA
> > Simon
> >
> >
> > _______________________________________________
> > Pyrex mailing list
> > Pyrex at lists.copyleft.no
> > http://lists.copyleft.no/mailman/listinfo/pyrex
>
>--
>Francesc Alted

Simon D.W. Frost, M.A., D.Phil.
Department of Pathology
University of California, San Diego
Antiviral Research Center
150 W. Washington St., Suite 100
San Diego, CA 92103
USA

Tel: +1 619 543 8080 x275
Fax: +1 619 298 0177
Email: sdfrost at ucsd.edu

The information transmitted in this e-mail is intended only for the
person(s) or entity to which it is addressed and may contain
CONFIDENTIAL and/or privileged material. Any review, re-transmission,
dissemination or other use of or taking of any action in reliance upon
this information by persons or entities other than the intended
recipient is prohibited. If you received this e-mail in error, please
contact the sender and delete/destroy the material/information from any
computer.








More information about the Pyrex mailing list