Afficher un message
Vieux 08/05/2008, 16h54   #8
Jim Langston
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: realloc problem, corrupt last item

Igal wrote:
> On May 8, 5:36 pm, "Jim Langston" <tazmas...@rocketmail.com> wrote:
>> Igal wrote:
>>> hay, i have this werid problem with my book adding function, this
>>> how it looks

>>
>>> book* AddBook(book *bp, unsigned *size) {
>>> ...
>>> //then i use realloc to allocate space for the new item in the bp
>>> pointer
>>> bp = (book*)realloc(bp, sizeof(book));

>>
>> realloc accepts the pointer to the prevoiusly allocated block, and
>> the new size. Since you are passing sizeof( book ) you are only
>> allocating enough space for 1 item.
>>
>> You probably meant something like:
>> bp = realloc( bp, sizeof( book ) * *size );
>> or
>> bp = realloc( bp, sizeof( book ) * (*size + 1) )
>> or something. I'm not sure how many additional items you want to
>> allocate for nor what size represents (new size or old size).

>
> in this function i need to reallocate only space for one new item.
> *size is the number of items i have in my array.
> correct me if i'm wrong, but if i realloc the size of my array+1,
> won't this allocate + n items to the original array?


No, realloc accpets the *new size* Total new size. How big you want the
array to be. Reguardless of how big it currently is. Which is current size
+ 1, or in your case (*size + 1) or with the source you gave before, n.

--
Jim Langston
tazmaster@rocketmail.com


  Réponse avec citation
 
Page generated in 0,06757 seconds with 9 queries