C question (memory allocation and access)

Conor P. Cahill cpcahil at virtech.uucp
Thu Nov 16 00:14:33 AEST 1989


In article <5322 at wpi.wpi.edu>, mhampson at wpi.wpi.edu (Mark A. Hampson) writes:
> void *block;
> block = malloc(block_siz);
> 
> simple enough...
> 
> I now wish to put two integers at the begining of this block of memory:
> 
> block = m;
> (block+sizeof(int)) = n;   <---  here is where I am running into probs.

You need to do the following:

	*((int *) block)  = m;
	*(((int *) block)+1) = n;

Note that this can cause core dumps if block does not point to a correctly
aligned address.  Your example used malloc to get the correct address, so
it will work properly.

Another solution would be to declare block as follows:

int * block;
block = (int *) malloc(...);
block[0] = m;

However this would give you problems when accessing the doubles.

A much cleaner solution would be to do the following:

struct t 
{
	int	m;
	int	n;
	double	d[1];
} * block;

int m = 10;
int n = 10;
int block_siz;

block_siz = sizeof(struct t) + ((m*n)-1)*sizeof(double);

block = (struct t *) malloc(block_siz);

Now you will be able to access your data as follows:

	block->m = m;
	block->n = n;
	block->d[15] = 15.23;
	block->d[m*n-1] = 16.32;



-- 
+-----------------------------------------------------------------------+
| Conor P. Cahill     uunet!virtech!cpcahil      	703-430-9247	!
| Virtual Technologies Inc.,    P. O. Box 876,   Sterling, VA 22170     |
+-----------------------------------------------------------------------+



More information about the Comp.std.c mailing list