Passing a dynamic array to a function

Discussion in 'C Programming' started by esmeco, Jun 5, 2010.

  1. esmeco

    esmeco

    Joined:
    Jun 5, 2010
    Messages:
    1
    Hello!
    I'm having some problems with dynamic arrays passed by reference.
    I have an add_employee() function which receives a pointer to a dynamic array of Employee structures.
    The purpose of this function is to add employees to an array, everytime this function is callled and reallocate the size of the array to accomodate new employees.
    The problem is I'm given an "Unhandled Exception" each time the function is called for the second time(to add a second employee to the array).The first time it works alright and the array is filled with the information passed on the call to gets();
    Here's the Employee function:

    Code:
    int add_employee(Employee **employee,int n_employees)
    {
    	
    	
    	n_employees++;
    
    	*employee=(Employee*) realloc(*employee,n_employees* sizeof(Employee));
    	
     
    	if(*employee== NULL)
    	{
    		fprintf(stderr, "Error alocating memory!");
    		exit(1);
    	}
    	
    
    	printf("Introduce employee name:\n");
    	fflush(stdin);
    	gets(employee[n_employees-1]->name);
    	employee[n_employees-1]->id=n_employees;
    	
    	
    	return n_employees;
    }
    


    If I use this code directly in main it works alright,but in this function it doesn't.
    What could I be doing wrong?
     
    esmeco, Jun 5, 2010
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. James Vanns
    Replies:
    7
    Views:
    7,169
    Evan Carew
    Jan 21, 2004
  2. Scott Lyons
    Replies:
    4
    Views:
    13,004
    Jeff Schwab
    May 3, 2004
  3. Jonathan Underwood
    Replies:
    2
    Views:
    690
    Simon Biber
    Aug 13, 2003
  4. Eps
    Replies:
    22
    Views:
    517
    nick_keighley_nospam@hotmail.com
    Jan 22, 2009
  5. deadpickle
    Replies:
    1
    Views:
    1,089
    Jens Thoms Toerring
    Nov 7, 2010
Loading...

Share This Page