You are not logged in.

#1 2009-08-16 23:32:47

delacruz
Member
From: /home/houston
Registered: 2007-12-09
Posts: 102

return an array in C

im trying to teach myself C and its not going to well.  How do i "pass" an array from myfunction() to inside the main function.


#include <stdio.h>

int main()
{
       int address;
    address = myfuntion();
    
      printf("%d\n",*address[2][2]); /* should print out 5 */

    return 0;
}


int myfunction() {
    
    int a[]={{3,2,5},{6,4,5}};
    
    
    return &a;
    
}

My code is all broken.  Someone please help smile

Offline

#2 2009-08-16 23:49:12

Xyne
Administrator/PM
Registered: 2008-08-03
Posts: 6,963
Website

Re: return an array in C

I would strongly recommend using internet searches to find answers to such questions. In this case, nearly all of the hits on the first page of a Google search for "return array from function in C" are directly relevant.

Take a look at this thread: http://ubuntuforums.org/showthread.php?t=128367

Last edited by Xyne (2009-08-16 23:50:07)


My Arch Linux StuffForum EtiquetteCommunity Ethos - Arch is not for everyone

Offline

#3 2009-08-16 23:52:51

tom5760
Member
From: Philadelphia, PA, USA
Registered: 2006-02-05
Posts: 283
Website

Re: return an array in C

So, the in myfunction:

int myfunction() {
    int a[]={{3,2,5},{6,4,5}};
    return &a;
}

There are multiple problems.  First, you want to return an array, but
you have the return type declared just as "int".  It should be something
like:

int * myfunction() {

Pointers and arrays are basically the same (you should read about this),
so if you want to return an array, this would be a proper return type.

Secondly, the variable "a" in myfunction is declared locally on the
stack, this means that it will be deleted for you automatically once
the function exits.  If you wish to allocate memory inside a function,
and then return that, you need to allocate on the heap, usually using
"malloc".  Like so:

int * myfunction() {
    /* Allocate space for 5 integers */
    int *a = malloc(5 * sizeof(int));
    a[0] = 0;
    a[1] = 1;
    a[2] = 2;
    a[3] = 3;
    a[4] = 4;
    return a;
}

This would allocate "a" to have enough room to hold 5 integers.  I see
in your function, you actaully have an array of arrays, this is slightly
more complicated:

/* NOTE: This function returns an array of arrays, not just a single
 * array */
int ** myfunction() {
    /* Allocate space for 5 integers */
    int *a = malloc(5 * sizeof(int));
    int *b = malloc(5 * sizeof(int));
    int i;
    for (i = 0; i < 5; i++) {
        a[i] = i;
        b[i] = i;
    }

    /* NOTE: Allocates space for 2 POINTERS TO INTs */
    int **c = malloc(2 * sizeof(int*));
    c[0] = a;
    c[1] = b;
    return c;
}

Now, to avoid memory leaks, you must call "free" on any memory space you
"malloc".  So somewhere in your main function or something, after you
are done, you should free your array.  Using the last example I just
wrote, you could do something like:

int main(int argc, const char[] * argv) {
    int ** myarray = myfunction();
    /* do some stuff */
    free(myarray[0]);
    free(myarray[1]);
    free(myarray);
}

Dynamic memory in C is a bit tricky at first, and there is lots of room
to make mistakes.  There is another option to this, you can instead pass
a pointer to "myfunction", which then sets its value.  Like this:

void myfunction(int * myarray, int size) {
    int i;
    for (i = 0; i < size; i++) {
        myarray[i] = i;
    }
}

int main(int argc, const char[] * argv) {
    int a[5];
    int b[5];
    int * c[2] = {a, b};

    myfunction(a, sizeof(a));
    myfunction(b, sizeof(b));
}

So, lots of options.  This last way is probably best, as you don't have
to worry about leaking memory, but dynamic memory is definitely
necessary in other cases.  C is a good language to know, good luck!

Offline

#4 2009-08-17 01:16:17

Trent
Member
From: Baltimore, MD (US)
Registered: 2009-04-16
Posts: 990

Re: return an array in C

tom5760 wrote:

Pointers and arrays are basically the same (you should read about this),

No offense, but no.  A pointer is an object whose value is a reference to another object.  An array is a set of contiguous objects with a single type.  Since arrays are not objects, you can't pass them in and out of functions.  Pointers are objects, so you can pass a pointer to the first element of an object (which works much the same way).  The OP's problem is treating an array as an object (returning it from a function) without realizing that the closest one can get in C is returning a pointer to its first element (which is useless, as you observed, when the array goes out of scope).

@delacruz:  tom5760 is correct and following his advice will get you to an almost-working program.  There's at least one other outright mistake (no function prototype for myfunction).  But all this is fairly advanced for someone new to C.  I recommend starting with something less complicated, and finding a good book or tutorial (preferably both) which will help you understand how problems are typically solved in C.  The C Programming Language, 2nd edition, by Kernighan and Ritchie, is a textbook worth its weight in gold.  The comp.lang.c FAQ (c-faq.com) is also a great help.  If you can manage to ignore all the spam, I also suggest reading comp.lang.c (http://groups.google.com/group/comp.lang.c/topics) to pick up pointers, but if you take my advice you won't post there for a while (I'll let you draw your own conclusions).

Offline

#5 2009-08-17 02:55:27

Intrepid
Member
Registered: 2008-06-11
Posts: 254

Re: return an array in C

I recommend using an object-oriented language, which makes this sort of thing MUCH simpler.  Rather than referencing an array by itself, an object/class will have functions to work on specific locations of its own array.  And you can easily reference an array of objects within the main program and call that object's functions which do all the work for you of returning and initializing values at that point of the array.  Trust me, while Pascal is a bit different than C/C++, the ease of programming that comes with using object-oriented programming is immense for many applications.  And you only have to dispose of the array of objects with a deconstructor rather than worrying about freeing multiple arrays.  Please just look this up, you'll understand.


Intrepid (adj.): Resolutely courageous; fearless.

Offline

#6 2009-08-17 13:47:09

Trent
Member
From: Baltimore, MD (US)
Registered: 2009-04-16
Posts: 990

Re: return an array in C

@Intrepid:  I'm not sure you mean what you say.  Object oriented programming is merely a way of approaching a problem.  Without a description of what the OP is trying to do, there is no way to say whether OOP is the right approach or not (and if you consider "I'm trying to teach myself C" to be the OP's mission, it certainly isn't).  Even if it is, using OOP does not alleviate the need to pass arrays into and out of functions, and it doesn't absolve the programmer of the responsibility to allocate and free memory.  Perhaps you mean to recommend that the OP use a "higher-level" language?

I personally like C and encourage delacruz to learn it.  It's certainly not suitable for all applications, but even then it's an educational experience and a help to understanding the quirks of other languages.  For someone who already knows Java and Perl, it's a good next step.

PS:  Ok, I think I've caused enough contention for today. big_smile

Offline

#7 2009-08-17 15:41:53

pauldonnelly
Member
Registered: 2006-06-19
Posts: 776

Re: return an array in C

Trent wrote:

Even if it is, using OOP does not alleviate the need to pass arrays into and out of functions, and it doesn't absolve the programmer of the responsibility to allocate and free memory.

Unless C++ is your idea of a viable OO language, it certainly does. tongue

Offline

#8 2009-08-17 16:35:59

Trent
Member
From: Baltimore, MD (US)
Registered: 2009-04-16
Posts: 990

Re: return an array in C

My point was that it's not OOP that includes those features.  They're great to have, and can be handy in conjunction with object oriented design.  They're also common features in languages that support OOP, but OOP does not mandate them.  For instance, it's possible to write a fully object oriented program in ANSI C, a language with no support for classes, pass-by-reference, garbage collection, automatic memory allocation, etc.  (Just take a look at Gtk+.)  OOP is not a language feature; it's an abstract model for understanding problems, and as such, it can't by itself take away any of the responsibilities associated with programming.  Using a different language can, and if that language just happens to include features that make OOP simpler to use, that's great too.

Offline

#9 2009-08-27 09:10:04

kevinwright
Member
Registered: 2009-08-27
Posts: 1

Re: return an array in C

Hi delacruz
Right now, I personally like C and encourage learning it.  It's certainly not suitable for all applications, but even then it's an educational experience and a help to understanding other languages.   

I follow this code:

int * myfunction () {
   
int *a = malloc (5 * sizeof(int));

        a[0] = 0;
       a[1] = 1;
    a[2] = 2;
        a[3] = 3;
        a[4] = 4;
       
    return a;

    }
Because using pointer it is easily to make application.

Offline

Board footer

Powered by FluxBB