1 Replies - 826 Views - Last Post: 25 June 2008 - 05:00 AM Rate Topic: -----

#1 maugly   User is offline

  • New D.I.C Head

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

Problem filling an array!

Post icon  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));
			perror("Can not allocate memory!");


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   User is offline

  • C Surfing ∞
  • member icon

Reputation: 119
  • View blog
  • 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)));

I hope this will help you. :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1