Re: Differences between one-dimensional arrays in Java and C
- From: Eric Sosman <esosman@xxxxxxxxxxxxxxxxxxx>
- Date: Mon, 02 May 2005 07:32:20 -0400
Tim Rentsch wrote:
> [allocate space for elements, padding, and pointers]
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:
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 .
- Follow-Ups:
- Re: Differences between one-dimensional arrays in Java and C
- From: Tim Rentsch
- Re: Differences between one-dimensional arrays in Java and C
- References:
- Differences between one-dimensional arrays in Java and C
- From: Paul Morrison
- Re: Differences between one-dimensional arrays in Java and C
- From: Malcolm
- Re: Differences between one-dimensional arrays in Java and C
- From: Axter
- Re: Differences between one-dimensional arrays in Java and C
- From: Tim Rentsch
- Differences between one-dimensional arrays in Java and C
- Prev by Date: Re: whats wrong with this pointer?
- Next by Date: Re: FR accent characters
- Previous by thread: Re: Differences between one-dimensional arrays in Java and C
- Next by thread: Re: Differences between one-dimensional arrays in Java and C
- Index(es):
Relevant Pages
|
|