Thursday, February 18, 2010

Memory allocation location is the cause of the errors..

Just got some usefull feedback from Tadej at Gtk+ Forums. As he points out:

'Arrays are allocated on a stack and their size is generally fixed. Alloc family of function on the other hand allocates memory from the heap.'

This would explain the issue over the incompatible types reported in the error messages. The code snippet Tad also posted gies the relevant key points. Array management in Tcl is so much easier!

/* gcc -Wall -g -o realloc_tadej realloc_tadej.c */

#include

typedef struct
{
int index;
char character;
}
Sample;

int
main( int argc,
char **argv )
{
int i;
Sample *tmp;

tmp = malloc( sizeof( Sample ) * 3 );
for( i = 0; i < 3; i++ )
{
tmp[i].index = i + 1;
tmp[i].character = i + 'a';
}

tmp = realloc( tmp, sizeof( Sample ) * 4 );
tmp[3].index = 4;
tmp[3].character = 'd';

return( 0 );
}

No comments: