|
|
C Code: Example for allocating memory (struct) with malloc (pointer to structure)
Below you find an example which allocates memory for 2 struct's.
We have two user-defined types (structs). It is extremely common to create pointers to structures,
so we can access variables within the struct with e.g. mybuffer->buffer1[i] or mybuffer->buffer2[i]
without knowing where the variables are located in the allocated memory heap.
malloc.c
// compile with: # gcc -o malloc malloc.c
#include <stdlib.h>
#include <stdio.h>
#define BUFFERSIZE 1024*1024
typedef struct {
unsigned int buffer1[BUFFERSIZE];
unsigned int buffer2[BUFFERSIZE];
char test[10];
} sample_buffer;
typedef struct {
unsigned int whichbuffer;
char test[10];
} buffer_info;
int main(int argc, char *argv[]) {
unsigned int i;
sample_buffer *mybuffer;
buffer_info *bufferinfo;
if (( mybuffer = (sample_buffer *) malloc( sizeof(sample_buffer) ) ) == NULL) {
printf("ERROR ALLOCATING mybuffer\n");
exit;
}
if (( bufferinfo = (buffer_info *) malloc( sizeof(buffer_info) ) ) == NULL) {
printf("ERROR ALLOCATING bufferinfo\n");
goto cleanup;
}
printf("finished malloc\n");
// fill allocated memory with integers and read back some values
for( i = 0; i < ( BUFFERSIZE); i = i + 1) {
mybuffer->buffer1[i] = i;
mybuffer->buffer2[i] = i + 100;
bufferinfo->whichbuffer = (unsigned int)(i/100);
// print some of the last values
if (i >= ( (BUFFERSIZE - 10 )) ) {
printf("mybuffer->buffer1[%d]=%d whichbuffer=%d\n", i,
mybuffer->buffer1[i], bufferinfo->whichbuffer);
printf("mybuffer->buffer2[%d]=%d\n", i, mybuffer->buffer2[i]);
}
}
strcpy(bufferinfo->test, "Captain");
printf("(C) 2006 by %s\n", bufferinfo->test);
memcpy(mybuffer->test, bufferinfo->test, 10);
printf("(C) 2006 by %s\n", mybuffer->test);
free(bufferinfo);
cleanup:
free(mybuffer);
return 0;
}
First we define our structures with "typedef struct". In main() we allocate memory with
the exact size of the structures. malloc returns a pointer to the memory just reserved for
us. We use this pointer to write integer numbers into buffer1 and buffer2. Furthermore
we copy a string with strcpy into bufferinfo->test and then copy the memory of bufferinfo->test
to mybuffer->test in the other struct.
Last-Modified: Sat, 04 Feb 2006 16:03:19 GMT
|
|