Problem filling an array!

Page 1 of 1

1 Replies - 826 Views - Last Post: 25 June 2008 - 05:00 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=55836&amp;s=a20144ddd135cc75ece8f3ae87812c90&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

#1 maugly

Reputation: 0
• Posts: 34
• Joined: 20-June 08

Problem filling an array!

Posted 25 June 2008 - 04:23 AM

Hi all!
I have a problem with this code:
it supposed to find the end of array (muzptr), to dynamicaly add another place to it and fill it.
Now muzptr is a dynamic array of a structure type named "music".
Can somebody tell me what's wrong with this code?

```	while (!(muzptr[e].makat==NULL)) e++;
muzptr=(music*) realloc(muzptr, 1*sizeof(music));
if(muzptr==NULL)
{
perror("Can not allocate memory!");
exit(1);
}
muzptr[e+1]=Muz;

```

thanx

This post has been edited by maugly: 25 June 2008 - 04:36 AM

Is This A Good Question/Topic? 0

Replies To: Problem filling an array!

#2 AmitTheInfinity

• C Surfing ∞

Reputation: 119
• Posts: 1,565
• Joined: 25-January 07

Re: Problem filling an array!

Posted 25 June 2008 - 05:00 AM

Your problem is with the size you mentioned in the realloc function. realloc can expand or reduce the allocated size to your pointer. you have asked it to allocate 1*sizeof(music) there. which will give you only 1 unit of structure music. So you are not adding 1 unit to array but actually reducing the size of your array!!!

You have to calculate actual size of your current array and need to add one more unit to it.

say it would be like this.

```muzptr=(music*) realloc(muzptr, ((e+1)*sizeof(music)));

```