Returning an array of int from a function 
Author Message
 Returning an array of int from a function

: This is a headache for me at the moment. I am beginning to get the feeling
: that all data must be entered in main to get the right results.
: I am trying to get the hang of pointers and arrays, unfortunately it
: hasn't happened yet. I have tried both the static and dynamic route. I
: either get segmentation faults or parse error. I tinkered with a suggested
: implimentation as follows:

: static int *Getdata(int *hbig)
: {
:      int i,big;
:      int *array;

:      printf("\n How big is the array?\n");
:      scanf("%d\n", big);

:      hbig = &big;
/* ### If you are trying to pass back the size of the array, then
 * you need '*hbig = big'.
 */
:      int *array = (int *)malloc((big)*sizeof(int));
/* ### You mean 'array = malloc(big * sizeof(int));' */
:      for (i=0; i<big;i++) {
:        printf("\n Enter your data \n");
:        scanf("%d", array[i]);
/* ### scanf() needs a pointer - try array + i */
:        }

:      return array;
: }

: This gives me a parse error before int  *array = (int*) malloc...etc.
: I don't get it. Is it really this hard to pass data between functions?

Well, the parse error is because you can declare variables only at
the start of a block, and in fact you've _re-declared_ 'array'.

: I really want to be able to pass structures but I haven't been able to
: pass data from one function to another. Are there any good books above
: "for dummies" and below "C problem solving &programming-KA barclay" ?
: I have about 6 months of c programming experience and am now really trying
: to get a more in depth understanding more or less.

Structures are easier to handle in many ways than arrays.  The array-
pointer relationships confuse most people learning C.

Will

--



Fri, 03 Nov 2000 03:00:00 GMT  
 Returning an array of int from a function

Quote:

> This is a headache for me at the moment. I am beginning to get the feeling
> that all data must be entered in main to get the right results.
> I am trying to get the hang of pointers and arrays, unfortunately it
> hasn't happened yet. I have tried both the static and dynamic route. I
> either get segmentation faults or parse error. I tinkered with a suggested
> implimentation as follows:

01> static int *Getdata(int *hbig)
02> {
03>      int i,big;
04>      int *array;
05>
06>      printf("\n How big is the array?\n");
07>      scanf("%d\n", big);
08>
09>      hbig = &big;
10>
11>      int *array = (int *)malloc((big)*sizeof(int));
12>
13>      for (i=0; i<big;i++) {
14>        printf("\n Enter your data \n");
15>        scanf("%d", array[i]);
16>        }
17>
18>      return array;
19> }

Quote:

> This gives me a parse error before int  *array = (int*) malloc...etc.
> I don't get it. Is it really this hard to pass data between functions?

You are declaring a variable "array" twice (once on line 4, once on line
11).  The parse err is, most likely, from the declaration on line 11,
which occurs after some non-declarative statements.  My C is somewhat
rusty (part of why I've taken to reading this group again), but if I
remember correctly, all declarations within a code-block must be
executed before any non-declarative statements.

If this is incorrect, will someone please flame me? :)

-Aaron Neerenberg
--



Fri, 03 Nov 2000 03:00:00 GMT  
 Returning an array of int from a function

On 13-Mai-98 22:29:03, T.A. Sherwood wrote in comp.lang.c.moderated:

Quote:
>This is a headache for me at the moment. I am beginning to get the feeling
>that all data must be entered in main to get the right results.
>I am trying to get the hang of pointers and arrays, unfortunately it
>hasn't happened yet. I have tried both the static and dynamic route. I
>either get segmentation faults or parse error. I tinkered with a suggested
>implimentation as follows:
>static int *Getdata(int *hbig)
>{
>     int i,big;
>     int *array;

>     printf("\n How big is the array?\n");
>     scanf("%d\n", big);

>     hbig = &big;

should be: big=*hbig;
Quote:

>     int *array = (int *)malloc((big)*sizeof(int));

should be: array=(int *)malloc(big*sizeof(int));
Quote:

>     for (i=0; i<big;i++) {
>       printf("\n Enter your data \n");
>       scanf("%d", array[i]);

should be: scanf("%d", array+i);
       or: scanf("%d", &(array[i]));

Quote:
>       }

>     return array;
>}
>This gives me a parse error before int  *array = (int*) malloc...etc.
>I don't get it. Is it really this hard to pass data between functions?

First, you try to assign the pointer to big (&big) to the variable hbig,
but what you want is the value hbig is pointing to (*hbig), assigned to
big.

Second, you try to declare a new varibale of type (int *) with the name
array, although you've already done so. Just leave out the declaration.

Third, scanf() needs a pointer to the variable you will store the result
in, not the variable itself. array is already a pointer, so array+i will
be a pointer to the i-th element in the memory pointed to by array.
&(array[i]) will also be the pointer to the i-th element in array.

Tor-Einar

--
Tor-Einar Jarnbjo

Tel: +49 30  41107080
--



Fri, 03 Nov 2000 03:00:00 GMT  
 Returning an array of int from a function

[snip]

Quote:
>static int *Getdata(int *hbig)
>{
>     int i,big;
>     int *array;

>     printf("\n How big is the array?\n");
>     scanf("%d\n", big);

>     hbig = &big;

>     int *array = (int *)malloc((big)*sizeof(int));
      ^^^^^

>     for (i=0; i<big;i++) {
>       printf("\n Enter your data \n");
>       scanf("%d", array[i]);
>       }

>     return array;
>}

>This gives me a parse error before int  *array = (int*) malloc...etc.
>I don't get it. Is it really this hard to pass data between functions?

You have already declared array at the top of the function.

Norman
--
Any sufficiently stupid Usenet post is indistinguishable from a troll.
(with apologies to A Clarke)
--



Fri, 03 Nov 2000 03:00:00 GMT  
 Returning an array of int from a function

Quote:

>Can anyone please provide an example of how to return an array of
>integers from a function in ANSI C?

The simplest solution is not to! Instead, pass the array you want to be
filled into the function as a parameter.  This won't always achieve what you
want, but it's good for most uses. Here's an example that returns an integer
array of n squares starting from a*a:

/* get_squares()
 * fills an array with n values a*a, (a+1)(a+1) ...
 * parameters: n - the size of the array to fill
 *        a - the first value to square
 *        squares - the array of squares
 * assumptions: n*n will not be to large to store in an int variable
 **************************************************************************/
void get_squares(int n, int a, int squares[])
{
    int index;
    for(index=0; index<n; index++)
        squares[index] = (index + a) * (index + a);

Quote:
}

This would be called something like this to get 81, 100, 121, 144, ...:

    int sq_array[10];
    ...
    get_squares(10, 9, sq_array);

Quote:

>I'll assume you use a pointer to memory and that you would also use
>malloc to dynamically allocate memory so that you won't be pointing to
>avariable of limited scope and duration.  I'm a little fuzzy on exactly
>how this should look...

This approach and that of using a static array within your function will
work, and others have submitted answers using these approaches. But they
have their own drawbacks.

Dynamic allocation means that the calling function needs to take
responsibility of explicitly freeing the memory.

Static allocation means that if you call the function a second time you lose
the results from the first call (unless you've copied them to a local array
within the calling function), and your function needs to know ahead of time
what the maximum size of the array will be.

I believe using a parameter will generally be more useful than trying to use
the return value.

Quote:

>I would appreciate your help and insight.

I hope this is useful. Feel free to pick holes in it if not.

Quote:
> - Ken

Glen.

--



Fri, 03 Nov 2000 03:00:00 GMT  
 Returning an array of int from a function


Quote:

> This is a headache for me at the moment. I am beginning to get the feeling
> that all data must be entered in main to get the right results.

Well, this is obviously not necessary.  But if you don't want the data
to be processed in their entirety in functions being called from the
function in which you enter them, you have two options.  Either store
them globally (rarely a good idea), or follow one of the methods
described in this thread for returning them from a function.  As I said,
I favor forgetting about using the return value, and letting the calling
function pass the address of the array to receive the data as an
argument.  This is how most of the functions in the standard library
treat strings, which are really arrays of char.

Quote:
> I am trying to get the hang of pointers and arrays, unfortunately it
> hasn't happened yet. I have tried both the static and dynamic route. I
> either get segmentation faults or parse error. I tinkered with a suggested
> implimentation as follows:
> static int *Getdata(int *hbig)
> {
>      int i,big;
>      int *array;
>      printf("\n How big is the array?\n");
>      scanf("%d\n", big);

I generally shy away from using "scanf" to read values from stdin, as it
is very inferior in handling incorrect user input.  It is better to read
input to a string with a function such as "fgets" (but do *not* ever use
gets), and then passing the resulting string to sscanf later.

Quote:
>      hbig = &big;

This will undoubtably *not* do what you want, though it is legal code,
and therefore will not produce an error from your compiler.  What you
are doing here is passing the *address* of the local variable "big" to
"hbig."  In so doing, you lose the address that was stored in hbig to
begin with, which was presumably the address of an outside variable in
which you intended to store the *value* of "big."  As it is, you have
lost any way for the "Getdata" function to access that variable.
Nothing will be stored there.

Presumably, what you intended was:

        *hbig = big;

While "hbig" is a pointer, the expression "*hbig" refers to whatever
variable "hbig" points to -- presumably an outside variable that passed
its address to "Getdata."  Therefore, the above statement assigns the
value of "big" to that variable.

Quote:
>      int *array = (int *)malloc((big)*sizeof(int));

       ^^^^^
The "int *" part in the beginning of this statement makes it look like a
variable definition, which in C must be either at the beginning of a
block (enclosed with { ... }) or outside any function whatsoever.  In
this case, it is not necessary at all, since you *already* defined
"array" earlier in the function.  Also, the (int *) cast in front of
"malloc" is unnecessary, and might prevent the compiler from emitting
helpful warning messages.  Neither is there any need to enclose "big" in
parentheses.  So:

        array = malloc(big*sizeof(int));

You could also have a check to see if malloc returned NULL.

Quote:
>      for (i=0; i<big;i++) {
>        printf("\n Enter your data \n");
>        scanf("%d", array[i]);
>        }

Again, the use of "scanf" is problematic if the user makes a mistake.
For instance, if he accidentally types a letter, "scanf" will return
without storing any value, but the letter would remain unread for the
next turn.  The loop would run through the entire remainder of "array"
without letting the user type any more input, and without storing
anything.

Quote:
>      return array;
> }

And as I said before, you have left it to the caller to "free" the
returned array after it has been used, which is a little awkward.

Quote:
> This gives me a parse error before int  *array = (int*) malloc...etc.
> I don't get it. Is it really this hard to pass data between functions?

You are hit by C's lack of "call-by-reference."  *All* function
arguments in C are passed by value, meaning that functions only work on
a local copy rather than the variable used in the calling function
(although arrays can give the illusion of being passed by reference).
The workaround is to use pointers as arguments.  Therefore, it is pretty
much *essential* to learn how to use pointers properly in C.

I know well how pointers work, and the common ways to pass arguments.
Once this knowledge is in, it gets easier to understand.

Quote:
> I really want to be able to pass structures but I haven't been able to
> pass data from one function to another. Are there any good books above
> "for dummies" and below "C problem solving &programming-KA barclay" ?
> I have about 6 months of c programming experience and am now really trying
> to get a more in depth understanding more or less.

I share the common opinion that the best introduction to C is the book
"The C Programming Language" by Kernighan & Ritchie.  It was *my*
introduction to the language.  It assumes some basic understanding of
programming in general, though.  However, it has a full section
dedicated to explaining the use of pointers.

I have never read the book "C For Dummies," but what I've heard,
suggests to me that it teaches some bad practices.  Part of my opinion
is based on reading a post from someone who claimed to have read it from
beginning to end, and still proved to understand nothing about either
function arguments or pointers.

And by all means, stay away from anything written by Herbert Schildt.

Yngvar
--



Sun, 05 Nov 2000 03:00:00 GMT  
 Returning an array of int from a function

Hi,

I didn't follow the complete thread but noticed a syntax error in the
sample and want to tell it to you:

                /* int *array = (int *)malloc((big)*sizeof(int)); */
                array = (int *)malloc((big)*sizeof(int));

If you compile your program after doing the above modification the parse
error will disappear, at least...

Dirk
--
------------------------------------------------------------------------
Dirk Gouders <gouders at spp.hpc.fujitsu.co.jp>                          
------------------------------------------------------------------------
--



Sun, 05 Nov 2000 03:00:00 GMT  
 Returning an array of int from a function


)This is a headache for me at the moment. I am beginning to get the feeling
)that all data must be entered in main to get the right results.
)I am trying to get the hang of pointers and arrays, unfortunately it
)hasn't happened yet. I have tried both the static and dynamic route. I
)either get segmentation faults or parse error. I tinkered with a suggested
)implimentation as follows:
)
)static int *Getdata(int *hbig)
){
)     int i,big;
)     int *array;
)
)     printf("\n How big is the array?\n");
)     scanf("%d\n", big);
)
)     hbig = &big;

This line probably needs to be

        *hbig = big;

I assume you want to get back big where it can be used
in code above this routine.

)
)     int *array = (int *)malloc((big)*sizeof(int));

This line should be

        array = (int *)malloc(big*sizeof(int));

or even better

        array = (int *)calloc(big,sizeof int);

[snip]

Mike
--
----
char *p="char *p=%c%s%c;main(){printf(p,34,p,34);}";main(){printf(p,34,p,34);}
This message made from 100% recycled bits.
I don't speak for DSC.         <- They make me say that.
--



Sun, 05 Nov 2000 03:00:00 GMT  
 Returning an array of int from a function

Well, actually you can declare a variable anywhere after a '{' (but it'll
only exist inside that block)

Quote:


>> This is a headache for me at the moment. I am beginning to get the
feeling
>> that all data must be entered in main to get the right results.
>> I am trying to get the hang of pointers and arrays, unfortunately it
>> hasn't happened yet. I have tried both the static and dynamic route. I
>> either get segmentation faults or parse error. I tinkered with a
suggested
>> implimentation as follows:

>01> static int *Getdata(int *hbig)
>02> {
>03>      int i,big;
>04>      int *array;
>05>
>06>      printf("\n How big is the array?\n");
>07>      scanf("%d\n", big);
>08>
>09>      hbig = &big;
>10>
>11>      int *array = (int *)malloc((big)*sizeof(int));
>12>
>13>      for (i=0; i<big;i++) {
>14>        printf("\n Enter your data \n");
>15>        scanf("%d", array[i]);
>16>        }
>17>
>18>      return array;
>19> }

>> This gives me a parse error before int  *array = (int*) malloc...etc.
>> I don't get it. Is it really this hard to pass data between functions?

>You are declaring a variable "array" twice (once on line 4, once on line
>11).  The parse err is, most likely, from the declaration on line 11,
>which occurs after some non-declarative statements.  My C is somewhat
>rusty (part of why I've taken to reading this group again), but if I
>remember correctly, all declarations within a code-block must be
>executed before any non-declarative statements.

>If this is incorrect, will someone please flame me? :)

>-Aaron Neerenberg
>--


--



Sat, 11 Nov 2000 03:00:00 GMT  
 
 [ 9 post ] 

 Relevant Pages 

1. Returning an array of int from a function

2. Returning Int array pointers from functions

3. Convert C++ (return type int, long, user-define, etc) function into COM/ATL

4. Calling int f(int (*f)(int)) like function in DLL from VB

5. Calling problem with function returning int

6. mem_fun not work on VC6 with function return int

7. Pointer to function returning pointer to function returning...

8. int pointer to int array

9. int to int array problem

10. Returning a 2D array from a function...

11. Returning pointer to array of structure from function

12. How to make a function return an array?

 

 
Powered by phpBB® Forum Software