RES: [Dev-C++] pointers of pointers structures memory allocation
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: <and...@su...> - 2003-03-21 11:32:28
|
<<This>> is what I like this list!!!
objetive answers and useful discussions
Thank you all
Andre
-----Mensagem original-----
De: Ricardo Lopez Ruiz [mailto:ri...@po...]
Enviada em: sexta-feira, 21 de marco de 2003 07:03
Para: Andre Macario Barros; Dev-C++
Assunto: Re: [Dev-C++] pointers of pointers structures memory allocation
Essentially you want to allocate memory for a char matrix in a dynamical
way.
(1) First you must allocate memory for the rows.
Imagine you need to store 50 strings, then p should point
to a pointer array able to allocate the 50 memory positions
of your 50 strings:
p = (char **) malloc(50*sizeof(char*));
(2) Second you want allocate in each row a string with a maximum
of 80 characters, then you should reserve this memory:
for(i=0 ; i<50 ; i++)
p[i] = (char *) malloc(80*sizeof(char));
(3) Now tou can store your strings:
for(i=0 ; i<50 ; i++)
{
printf("\n Give me a char string: ");
gets(p[i]);
}
(4) Finally you free the allocated memory in this way:
for(i=0 ; i<50 ; i++) free(p[i]);
free (p);
Hope this can help you.
Ricardo.
|