Thread: Passing arrays

  1. #1
    Registered User
    Join Date
    Aug 2007
    Posts
    270

    Question Passing arrays

    How could I do the following:
    Code:
    int[] somefunc();
    
    int main(void){
    	int i;
        int array = somefunc();
    	for(i=0; i<10; i++)
    		printf("%d\n", array[i]);
    }
    
    int[] somefunc()
    {
    	int size = 10, i;
    	int array[size];
    	for(i=0; i<size; i++)
    		array[i] = i;
    		
    	return array;
    }
    I set the array size and contents in somefunc() and the return the array to the main.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    int *somefunc( ... )
    {
        int *notreallyanarray = malloc( sizeof *notreallyanarray * sizeyouwant );
        ...
        return notreallyanarray;
    }
    The word you're wanting to search for is 'dynamic'.


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

  3. #3
    Registered User
    Join Date
    Aug 2007
    Posts
    270
    But like how do you return it to the main which doesn't know the size?

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    I just showed you how. The size however isn't able to be determined with just a pointer alone. You will need to keep track of that on your own.


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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. More trouble passing arrays
    By Rad_Turnip in forum C Programming
    Replies: 2
    Last Post: 04-04-2006, 08:11 PM
  2. Passing pointers to arrays of char arrays
    By bobthebullet990 in forum C Programming
    Replies: 5
    Last Post: 03-31-2006, 05:31 AM
  3. Having Trouble Passing typedef Arrays to a Function
    By jlharrison in forum C Programming
    Replies: 1
    Last Post: 03-27-2006, 12:06 PM
  4. Help Understanding Passing Arrays To Functions
    By jrahhali in forum C++ Programming
    Replies: 7
    Last Post: 04-10-2004, 02:57 PM
  5. Replies: 4
    Last Post: 11-05-2001, 02:35 PM