svata <sv******@centr um.czwrote:
I wonder how to resize such array of structures using realloc()?
#include <stdio.h>
#include <stdlib.h>
#define FIRST 7
typedef struct {
char *name;
int i;
int j;
} STRUCTURE;
STRUCTURE **p_structure;
int main() {
Make that
int main( void )
since your main() takes no arguments.
p_structure = (STRUCTURE **) malloc(FIRST * sizeof(STRUCTUR E));
Don't cast the return value of malloc(), it only hides your mistake
should you have forgotten to include <stdlib.h>. But, more important,
you allocate here memory for 7 (FIRST) such structures. malloc() returns
a pointer to the start of this memory, which is of type 'STRUCTURE *'
(malloc() actually returns a void pointer but "STRUCTURE *' is the
correct type of a pointer to that memory). But you assign it instead
to a pointer that has type 'STRUCTURE **'. That, combined with your
use of the words "2D array" in the subjct line, leads to the suspicion
that you actually don't want to allocate memory for something that has
similar properties as an array of stuctures, but something more compli-
cated and similar to a 2D array of such structures. And that's what you
definitely won't get with that allocation, whatever the type of the
pointer you assign the return value of malloc() to. So, instead of
starting to guess what you might have intended I think it's better to
ask you to specify a bit more clearly what you intend to do here: do
you just want memory for a simple set of structures or do you want
something like a 2D array of such structures. In the first case you
could "repair" your program by simply defining 'p_structure' as
STTRUCTURE *p_structure;
Perhaps you thenn also might want to replace the line for the allo-
cation by
p_structure = malloc(FIRST * sizeof *p_structure);
because that way you don't have to change that line anymore if you
should decide to change the type of 'p_structure' sometime later.
You also write something about realloc() but I can't see any
use or mentioning of realloc() in the code you posted. But, of
course, you can use realloc() to resize the amount of memory
you obtained from malloc() - that's what realloc() was invented
for.
if ( p_structure == NULL ) {
printf("Failed to allocate memory, exiting...");
return 1;
}
It's good to see that you check that what malloc() returned!
}
Since main() returns an int, here's a missing line with a return
value...
Regards, Jens
--
\ Jens Thoms Toerring ___
jt@toerring.de
\______________ ____________
http://toerring.de