Re: using realloc()
Jens.Toerring_at_physik.fu-berlin.de
Date: 07/30/04
- Next message: Phlip: "Code-and-Fix for GUIs [Was: Rework]"
- Previous message: Phlip: "Re: Rework [Was: Static vs. Dynamic typing...]"
- In reply to: John Hanley: "Re: using realloc()"
- Next in thread: Jens.Toerring_at_physik.fu-berlin.de: "Re: using realloc()"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 29 Jul 2004 23:31:51 GMT
John Hanley <jdhanley@telusplanet.net> wrote:
>> I start out with int * elements = (int *) malloc(sizeof(int)),
>>
>> then in my next function, I pass it 'elements' which I reallocate memory
> for
>> in order to add another element dynamically:
>>
>> elements=(int *)realloc(elements, sizeof(int)*(j+1));
>>
>> When debugging this in gdb, I notice that when j=2, and I realloc, my
>> address of 'elements' changes. But when j=1, it was fine.
> When thinking about this further, I am guessing that it has something to do
> with alignment in memory. Does that sound right?
No, not at all, see my previous post.
> If so, is there a way around this to make sure it's always going to be
> pointing to the same memory address? This is only because I pass this
> pointer around to a couple of functions. If the second function changes the
> address, the first function will still be pointing to the original address.
If there is the need to increase the memory a pointer is pointing to
in a function you don't pass just the pointer itself to a function,
but a pointer to that pointer. That way you can change what it's
pointing to with the change becoming visible to the calling functing.
Here's a rather contrived example:
#include <stdio.h>
#include <stdlib.h>
int mail( void )
{
int *p = malloc( 100 );
if ( p == NULL )
printf( "Couldn't make p point to even 100 int's\n" );
exit( EXIT_FAILURE );
}
if ( increase_p( &p ) == 0 )
printf( "Wow, p now points to 500 int's!\n" );
else
printf( "Sorry, couldn't get more, p still points to 100 int's\n" );
...
}
int increase_p( int **p )
{
int *new_p = realloc( *p, 500 * sizeof **p );
if ( new_p != NULL )
{
*p = new_p;
return 0;
}
return -1;
}
Admittedly, pointers to pointers can be a bit scary at first, but after
a rather short time you will get the hang of it - and they are the only
way to go in these cases. Just wait 'til you have to deal with triple
pointers;-)
Regards, Jens
-- \ Jens Thoms Toerring ___ Jens.Toerring@physik.fu-berlin.de \__________________________ http://www.toerring.de
- Next message: Phlip: "Code-and-Fix for GUIs [Was: Rework]"
- Previous message: Phlip: "Re: Rework [Was: Static vs. Dynamic typing...]"
- In reply to: John Hanley: "Re: using realloc()"
- Next in thread: Jens.Toerring_at_physik.fu-berlin.de: "Re: using realloc()"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|