Copy array into a Dynamic array

This is a discussion on Copy array into a Dynamic array within the C Programming forums, part of the General Programming Boards category; how would one go about allocating a dynamic array? and then copying an array into that dynamic array?...

  1. #1
    Registered User
    Join Date
    Apr 2010
    Posts
    58

    Copy array into a Dynamic array

    how would one go about allocating a dynamic array? and then copying an array into that dynamic array?

  2. #2
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    You use malloc to allocate the necessary space, and then just copy that many elements from the other array into the newly allocated one.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  3. #3
    Registered User
    Join Date
    Apr 2010
    Posts
    58
    ok.

    here is the new dynamic array

    Code:
    int copyarray(int, *ary_nbr, int ele)
    {
    	int *dyn_ary; // 1-dim array
    
    	dyn_ary = malloc(ele * sizeof(int));
    }
    what code would copy it

  4. #4
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Ok, so now just copy ele ints from another array into it using a simple for loop. Also, don't forget to free the dyn_ary pointer at the end of your program.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  5. #5
    Registered User
    Join Date
    Apr 2010
    Posts
    58
    so this should work? and i returned the dynamic array correctly?

    Code:
    int copyarray(int *ary_nbr, int ele)
    {
    	int i = 0;
    
    	/* allocate 1-dim dynamic array */
    	int *dyn_ary; 
    	dyn_ary = malloc(ele * sizeof(int));
    
    	for (i = 0; i < ele; i++)
    	{
    		dyn_ary[i] = ary_nbr[i];
    		
    	}
    	
    	free(dyn_ary);
    	return dyn_ary[i];
    
    
    }
    Last edited by pantherman34; 05-01-2010 at 07:38 PM.

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    No. You'd need to return a pointer to the memory allocated. Also, you don't free something and then try to return it or use it. Once you free it, it's gone. Don't try to pretend it's still there.


    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    Registered User
    Join Date
    Apr 2010
    Posts
    58
    Code:
    int copyarray(int *ary_nbr, int ele)
    {
    	int i = 0;
    
    	/* allocate 1-dim dynamic array */
    	int *dyn_ary; 
    	dyn_ary = (int*) malloc(ele * sizeof(int));
    
    	/* copy ary_nbr into dyn_ary*/
    	for (i = 0; i < ele; i++)
    	{
    		dyn_ary[i] = ary_nbr[i];
    		
    	}
    	
    	return *dyn_ary;
    	free(dyn_ary);
    }
    hows that look
    Last edited by pantherman34; 05-01-2010 at 07:44 PM.

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    No. You can't do anything in a function after return is encountered. The function stops at that point. You only free something when you're all done with it. If you're trying to use it in another function, you don't try to free it. You try to free it when you're really all done with it. Plus, you need to return a pointer, not an integer:
    Code:
    int *stuff( size_t x )
    {
        int *p = malloc( x * sizeof( *p ) );
    
        return p;
    }
    
    ... some place else ...
    
    int *foo;
    ...
    foo = stuff( 5 );
    
    ... do things with foo ...
    
    free( foo );
    Quzah.
    Hope is the first step on the road to disappointment.

  9. #9
    Registered User
    Join Date
    Apr 2010
    Posts
    58
    here is the corrected code
    Code:
    int copyarray(int *ary_nbr, int ele)
    {
    	int i = 0;
    
    	/* allocate 1-dim dynamic array */
    	int *dyn_ary; 
    	dyn_ary = (int*) malloc(ele * sizeof(int));
    
    	/* copy ary_nbr into dyn_ary*/
    	for (i = 0; i < ele; i++)
    	{
    		dyn_ary[i] = ary_nbr[i];
    		
    	}
    	
    	return dyn_ary;
    }
    is that the correct way to copy the data? does one use the [i] for the dynamic array to copy it?

  10. #10
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Correct your function header, you need to return a pointer not an int, like quzah said.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  11. #11
    Registered User
    Join Date
    Apr 2010
    Posts
    58
    ok...im trying to take the array from the first function and return it to main...and then take the array back to the sort function...

    here are the prototypes:
    Code:
    int *copyarray(int *ary_nbr, int ele);
    
    int sortarray (int *dyn_ary, int ele);
    here are the bodies:
    Code:
    int *copyarray(int *ary_nbr, int ele)
    {
    	int i = 0;
    
    	/* allocate 1-dim dynamic array */
    	int *dyn_ary; 
    	dyn_ary = (int*) malloc(ele * sizeof(int));
    
    	/* copy ary_nbr into dyn_ary*/
    	for (i = 0; i < ele; i++)
    	{
    		dyn_ary[i] = ary_nbr[i];
    		
    	}
    	
    	return dyn_ary[];
    }
    
    int sortarray (int *dyn_ary, int ele)
    {
    	int j;
    	int i;
    	int temp;
    
    	/* perform bubble sort */
    	for( i=0; i<ele; i++)
    	{
    		for(j=0; j<ele-1; j++)
    		{
    			if( dyn_ary[j] > dyn_ary[j+1])
    			{
    				temp = dyn_ary[j+1];
    				dyn_ary[j+1] = dyn_ary[j];
    				dyn_ary[j] = temp;
    			}
    		}
    	}
    }
    and here are the function calls in main: i didnt declare dyn_ary in main, since im returning dyn_ary from copyarray i dont have to right?

    Code:
    dyn_ary = copyarray (ary_nbr, elements);
    
    	sortarray (dyn_ary, elements);
    Last edited by pantherman34; 05-01-2010 at 09:30 PM.

  12. #12
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Quote Originally Posted by pantherman34 View Post
    ok...im trying to take the array from the first function and return it to main...and then take the array back to the sort function...

    here are the prototypes:
    Code:
    int *copyarray(int *ary_nbr, int ele);
    
    int sortarray (int *dyn_ary, int ele);
    here are the bodies:
    Code:
    int *copyarray(int *ary_nbr, int ele)
    {
    	int i = 0;
    
    	/* allocate 1-dim dynamic array */
    	int *dyn_ary; 
    	dyn_ary = (int*) malloc(ele * sizeof(int));
    
    	/* copy ary_nbr into dyn_ary*/
    	for (i = 0; i < ele; i++)
    	{
    		dyn_ary[i] = ary_nbr[i];
    		
    	}
    	
    	return dyn_ary[];
    }
    
    int sortarray (int *dyn_ary, int ele)
    {
    	int j;
    	int i;
    	int temp;
    
    	/* perform bubble sort */
    	for( i=0; i<ele; i++)
    	{
    		for(j=0; j<ele-1; j++)
    		{
    			if( dyn_ary[j] > dyn_ary[j+1])
    			{
    				temp = dyn_ary[j+1];
    				dyn_ary[j+1] = dyn_ary[j];
    				dyn_ary[j] = temp;
    			}
    		}
    	}
    }
    and here are the function calls in main: i didnt declare dyn_ary in main, since im returning dyn_ary from copyarray i dont have to right?

    Code:
    dyn_ary = copyarray (ary_nbr, elements);
    
    	sortarray (dyn_ary, elements);
    You do have to declare it. main() has no idea who dyn_ary refers to. Also, note that unless you need that pointer later on for other things, you can just make the call in a nested fashion:

    sortarray(copyarray(ary_nrb,elments), elements);

    This is basically saying, sort the array that the pointer I am returning from copyarray points to and that contains <elements> numbers.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  13. #13
    Registered User
    Join Date
    Apr 2010
    Posts
    58
    i do need the pointer to sort the same array different ways... but first i want to get this sort working.

    Im having problems linking it all together...my program is in different files...

    here is my main.c

    Code:
    #pragma warning(disable : 4996)
    #include <stdio.h>
    #include <stdlib.h>
    #include "type-proto.h"
    
    
    #define bool int
    #define true 1
    #define false 0
    
    #define	in_filename "Prog2Data.txt"
    #define out_filename "Report.txt"
    #define maxsize 100
    
    
    
    int main(int argc,char *argv[])
    {	
    	/* declare array */
    	int ary_nbr[maxsize];
    	
    
    	/* I/O pointers */
    	FILE *InFile, *OutFile;
    
    	/* error checking */
    	bool file_error_flag;
    
    	/* Open the file to read */
    	file_error_flag = false;
    
    	InFile = fopen(in_filename, "r");
    	if (InFile == NULL) 
    	{
    		printf("Error opening \"%s\"\n\n", in_filename);
    		file_error_flag = true;
    	}
    
    	/* Creates and Opens the Write File */
    	OutFile = fopen(out_filename, "w");
    	if (OutFile == NULL)
    	{
    		printf("Error opening \"%s\"\n\n", out_filename);
    		file_error_flag = true;
    	}
    
    	if (file_error_flag)
    	{
    		printf("\nProgram terminated due to FILE error!\n\n");
    		/* Identify problem file and close files that are open */
    		if (InFile == NULL)
    			printf("Error with %s\n",in_filename);
    		else
    			fclose(InFile);
    		if (OutFile == NULL)
    			printf("Error with %s\n",out_filename);
    		else
    			fclose(OutFile);
    	}
    	else /* Files open successfully */
    	{	
    
    	/* elements catches # of actual data loaded */
    	int elements = 0;
    
            /* the dynamic array */
            int *dyn_ary;
    
    	/* runs & catches return from load function */
    	elements = load(InFile, ary_nbr, maxsize);
    
    	
    	dyn_ary = copyarray (ary_nbr, elements);
    
            /* prints actual data loaded in array pre sort */
    	printtab (OutFile, dyn_ary, elements);
    
    
    	sortarray (dyn_ary, elements);
    
    
    	/* prints actual sorted data */
    	printtab (OutFile, dyn_ary, elements);
    
    	/* close files */
    	fclose(InFile);
    	fclose(OutFile);
    	}	
    
    	/* else file_error_flag */
    	return file_error_flag;
    }
    here is my bodies.c
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include "type-proto.h"
    
    
    
    int load (FILE *InFile, int *ary_nbr, int size)
    {
    	/* array sunscript, loop control, and # actual data loaded */
    	int i; 
    	
    	/* loads data from file into array */
    	i = 0;
    	while((fscanf(InFile, "%i", &ary_nbr[i]) != EOF) && ( i < size))
    	{
    		i++; 
    	}
    
    	/* returns actual data loaded to elements */
    	return i;
    }
    
    void printtab (FILE *OutFile, int *ary_nbr, int ele)
    {
    	int i;
    	for (i = 0; i < ele; i++)
    	{
    	fprintf(OutFile, "%7d", ary_nbr[i]);
    	printf("%7d", ary_nbr[i]);
    		if(i%10==9)
    		{
    			fprintf(OutFile, "\n");
    			printf("\n");
    		}
    	}
    }
    int *copyarray(int *ary_nbr, int ele)
    {
    	int i = 0;
    
    	/* allocate 1-dim dynamic array */
    	int *dyn_ary; 
    	dyn_ary = (int*) malloc(ele * sizeof(int));
    
    	/* copy ary_nbr into dyn_ary*/
    	for (i = 0; i < ele; i++)
    	{
    		dyn_ary[i] = ary_nbr[i];
    		
    	}
    	
    	return dyn_ary;
    }
    
    int sortarray (int *dyn_ary, int ele)
    {
    	int j;
    	int i;
    	int temp;
    
    	/* perform bubble sort */
    	for( i=0; i<ele; i++)
    	{
    		for(j=0; j<ele-1; j++)
    		{
    			if( dyn_ary[j] > dyn_ary[j+1])
    			{
    				temp = dyn_ary[j+1];
    				dyn_ary[j+1] = dyn_ary[j];
    				dyn_ary[j] = temp;
    			}
    		}
    	}
    }
    and here is my type-proto.h
    Code:
    int load (FILE *InFile, int *ary_nbr, int size);
    
    void printtab (FILE *OutFile, int *ary_nbr, int ele);
    
    int *copyarray(int *ary_nbr, int ele);
    
    int sortarray (int *dyn_ary, int ele);
    i must copy the array in copyarray (which i think i have, but the call in main is probably incorrect), then pass the dyn_ary to main, then pass it back to the sort array, then printtab the sorted array

  14. #14
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Do you need to have all these files? Is that a requirement?

    If not just copy paste everything else in main.c, for the size/scope of this application I don't see why you would bother with that.

    If you are using an IDE, the IDE should be able to link everything for you. If you are not using an IDE, you could write a makefile yourself and make the executable.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  15. #15
    Registered User
    Join Date
    Apr 2010
    Posts
    58
    yes its a requirement to have all these files. how would i use an ide? im using visual studio

    EDIT*** i must be becoming better at programming, because i have it working!!! lol
    Last edited by pantherman34; 05-01-2010 at 10:57 PM.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. array copy problem
    By Witch in forum C Programming
    Replies: 3
    Last Post: 03-22-2010, 07:00 PM
  2. Dynamic array allocation
    By Maulrus in forum C++ Programming
    Replies: 7
    Last Post: 03-09-2010, 05:08 PM
  3. Dynamic Array Allocation function
    By P4R4N01D in forum C++ Programming
    Replies: 6
    Last Post: 05-15-2009, 02:04 AM
  4. Dynamic array?
    By BSmith4740 in forum C Programming
    Replies: 8
    Last Post: 06-30-2008, 11:52 AM
  5. Replies: 4
    Last Post: 11-02-2006, 10:41 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21