Article View: comp.std.c
Article #909Re: C question (memory allocation and access)
From: Conor P. Cahill
Date: Wed, 15 Nov 1989 13:14
Date: Wed, 15 Nov 1989 13:14
59 lines
1897 bytes
1897 bytes
In article <5322@wpi.wpi.edu>, mhampson@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 |
+-----------------------------------------------------------------------+
Technical Details
Message-ID:
<1989Nov15.131433.3197@virtech.uucp>Path:
arc1-ca.pugleaf.net!utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!uunet!virtech!cpcahilReferences:
<5322@wpi.wpi.edu>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!uunet!virtech!cpcahil From: cpcahil@virtech.uucp (Conor P. Cahill) Newsgroups: comp.std.c Subject: Re: C question (memory allocation and access) Keywords: memory access Message-ID: <1989Nov15.131433.3197@virtech.uucp> Date: 15 Nov 89 13:14:33 GMT References: <5322@wpi.wpi.edu> Distribution: usa Organization: Virtual Technologies Inc. Lines: 59