Thread: Union of arrays

  1. #1
    Registered User Makaila's Avatar
    Join Date
    Oct 2009
    Posts
    10

    Unhappy Union of arrays

    I have to make a union of two arrays and each of them has <=20 elements. So I was thinking to form the third array which will contain the elements for a union. Some like this:

    The union is a function which will be called from main.

    Code:
    void unija(int *x, int *y, int lenx, int leny)
    {
    	int i,j,k,niz[???]; // I have a problem with this length, I tried to proceed it from main
                                      // it would be a sum of lengths of this two arrays but I have 
                                      // probably made a mistake since it doesn't work
    
    	for(i=0;i<lenx;i++)
    	{
    		for(j=0;j<leny;j++)
    		{
    			if(*(x+i)!=*(y+j))
    				niz[k]=*(x+i);
    				
                    k++;
    		}
    		
    		for(j=0;j<leny;j++)
    		{
    			if(*(x+i)=<>*(y+j))
    				niz[k]=*(y+i);
    		k++;
    		}
    	}
    }
    anyway, I got stuck here, and I'm not sure if this code is good for anything anymore as I made changes so many times. I hope you could help me.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    By union, you mean not an actual union in the C-sense of the word, but rather in the dictionary definition of the word (to combine). You can only have variable length arrays if you use C99. If you don't, or if you don't want to, then use dynamic memory:
    Code:
    void foo( int x, int y )
    {
        int *array;
    
        array = malloc( x + y * sizeof *array );
        ... do stuff to 'array'...
        free( array );
    }
    Something like that. Basically we're saying "allocate x + y number of elements, each being the size of an integer".


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

  3. #3
    Registered User Makaila's Avatar
    Join Date
    Oct 2009
    Posts
    10
    ok, thanks! I have managed to put this array in function

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 10-29-2006, 05:04 AM
  2. Union 2 arrays
    By sugie in forum C++ Programming
    Replies: 2
    Last Post: 10-20-2005, 10:51 AM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. union of two arrays
    By chaitanya in forum C Programming
    Replies: 2
    Last Post: 09-12-2004, 05:53 AM
  5. Sorting a Union
    By andy in forum C Programming
    Replies: 4
    Last Post: 11-21-2001, 10:12 AM

Tags for this Thread