Re: Differences between one-dimensional arrays in Java and C



Tim Rentsch wrote:

Now here's an interesting question. I believe it's possible to construct a 2D array (with both dimensions non-constant) by calling malloc only once. For example:

> [allocate space for elements, padding, and pointers]

Since the memory returned by malloc is suitably aligned for all types, both 'elements' and 'array' are suitably aligned for objects of their respective types. Note that 'extra_space' is calculated so that 'element_space + extra_space' is a multiple of 'pointer_size'.

Each of the two areas of memory (at 'elements' and 'array') is used
only to store/retrieve objects of their respective types.

According to my best understanding the code above should work in
standard C.  But I put it as a question - does anyone have an argument
to the contrary?

Looks all right. A type's alignment requirement must be a divisor of its size (otherwise arrays wouldn't work), so the `extra_space' will be enough padding to get the pointers to align properly. In fact, `extra_space' may be more than is needed; if you really want to be parsimonious you can use a dodge that someone posted here a year or two ago:

	#include <stddef.h>
	#define alignof(T) offsetof(struct {char c; T t;}, t)

    Manually-inserted padding can also be used to write portable
versions of "the struct hack" for C90 implementations (C99
introduced an easier notation).

--
Eric Sosman
esosman#acm-dot-org.invalid
.



Relevant Pages

  • Re: Reentrant problem with inet_ntoa in the kernel
    ... 2006/11/3, Brooks Davis: ... >>> to store the result. ... And it returns the address of the array to the ... >>> calling it. ...
    (freebsd-net)
  • Re: Base Normal Form
    ... > What's the difference between calling a table a list of tuples, ... In some formal contexts, I think a list is either empty, or consisting ... In contrast, an array is ... > I'm hazy on the distinction between a relation and a relvar. ...
    (comp.databases.theory)
  • Embedding Python in C
    ... but modifiying it now as a function inside my C/C++ code. ... Problem started when I started passing an array as an argument. ... The code for argument building and calling are as follows: ... lies in the list building process. ...
    (comp.lang.python)
  • Re: Need a method to send byte arrays from Unmanaged C DLL to VB
    ... before calling the C routine. ... you can use a StringBuffer instead of a byte array. ... from a C DLL to VB? ... with ByRef Byteas a parameter, then treating it in C as a pointer to ...
    (microsoft.public.dotnet.languages.vb)
  • Re: Is it posible to create COM in .Net C#
    ... > What security checks are there and how can they be turned off? ... In order to make it behave like an array passed by ... > reference the array is copied again when control returns to COM. ... in order to suppress a security walk when calling into COM (or unmanaged ...
    (microsoft.public.dotnet.languages.csharp)