jjflyV7
jjflyV7

Reputation: 55

Functions returning arrays

I need my function to return an array that will then go into the next function. I know based on some research that I have to use a pointer to get this done. however when I run this code I get memory addresses or what appears to me memory addresses (if its not the address its a huge number) in my results.

The problem happens when the array needs to change functions. The two individual functions run fine on there own as intended.

Here is my code:

int main(void) 
{
    int y = 0, x[10];
    int *p;
    y = capturingNumberTimesLoopRuns();
    p = PopulateArray(y);
    searchArray(x);
}

int capturingNumberTimesLoopRuns (void)
{
    int y = 0;
    while (y == 0) 
    {
        printf("Please enter the quantity of numbers you wish to enter.\n");
        printf("Enter a number between 1 and 10: ");
        scanf("%d", &y);
        if (y < 1 || y > 10)
        {
            printf("Invalid Selection! Please Try Again.\n");
            y = 0;
        }
    }
    return y;
}

int * PopulateArray(int y) 
{
    int i;
    int x[10];
    int a = 1;
    for (i = 0; i < y; i++) 
    {
        printf("Please enter number %d: ", a);
        scanf("%d", &x[i]);
        a++;
    }
    return x;
}

void searchArray(int x[]) 
{
    int i, a = 0, numberOfTimes = 0, average = 0;
    for (i = 0; x[i] != 0; i++) 
    {
        if (x[i] % 3 == 0) 
        {
            a += x[i];
            numberOfTimes += 1;
        }
    }
    average = a / numberOfTimes;
    printf("%d\n", a);
    printf("average = %d", average);
}

Upvotes: 0

Views: 70

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84521

Your research is correct. The way to handle operations on an array within a function is to pass a pointer to the array to your function. You can then operate on the array at-will in the function without the requirement of returning a pointer when your function return. (you can still return a pointer to the array for convenience of course)

Beyond passing a pointer to your array, you will need to pass the size of your array as well (or use a global to track the size of your array - not preferable as you want to avoid the use of globals unless totally necessary). For example, your populatearray function could be written as follows:

/* pass pointer to array and size to function */
int *populatearray (int *x, int sz) 
{
    int i, a = 1;

    for (i = 0; i < sz; i++)     {
        printf ("Please enter number %2d: ", a++);
        scanf ("%d", &x[i]);
    }

    return x;
}

(the return here is for convenience and is not required as your array is declared in main())

This allows you to avoid dynamic allocation, maintaining a pointer to the allocated block of memory and the responsibility for freeing that memory when it is no longer needed. There is nothing wrong with dynamically allocating memory, but it is an additional layer of complication that new C programmers have to deal with.

A short example using your populatearray could work as follows:

#include <stdio.h>

enum { MAXI = 10 };  /* avoid 'magic' numbers, use proper constants */

int *populatearray (int *x, int y);
void prnarray (int *x, int sz);

int main (void) {

    int x[MAXI] = {0};

    populatearray (x, MAXI);
    prnarray (x, MAXI);

    return 0;
}

/* pass pointer to array and size to function */
int *populatearray (int *x, int sz) 
{
    int i, a = 1;

    for (i = 0; i < sz; i++)     {
        printf ("Please enter number %2d: ", a++);
        scanf ("%d", &x[i]);
    }

    return x;
}

/* pass pointer to array and size to function */
void prnarray (int *x, int sz) 
{
    int i;
    for (i = 0; i < sz; i++)
        printf (" x[%2d] : %d\n", i, x[i]);
}

Example Use/Output

$ ./bin/array_pass
Please enter number  1: 10
Please enter number  2: 20
Please enter number  3: 30
Please enter number  4: 40
Please enter number  5: 50
Please enter number  6: 60
Please enter number  7: 70
Please enter number  8: 80
Please enter number  9: 90
Please enter number 10: 100
 x[ 0] : 10
 x[ 1] : 20
 x[ 2] : 30
 x[ 3] : 40
 x[ 4] : 50
 x[ 5] : 60
 x[ 6] : 70
 x[ 7] : 80
 x[ 8] : 90
 x[ 9] : 100

(While not an error, the standard coding style for C avoids caMelCase variables in favor of all lower-case. See e.g. NASA - C Style Guide, 1994)

Let me know if you have any additional questions.

Upvotes: 2

yaman
yaman

Reputation: 769

The array is destroyed when the function returns due to its auto storage. Try allocating memory dynamically from the heap (ie malloc()) as:

int * PopulateArray(int y) 
{
    int i;
    int *x = malloc(10*sizeof(int));

    int a = 1;
    for (i = 0; i < y; i++) 
    {
        printf("Please enter number %d: ", a);
        scanf("%d", &x[i]);
        a++;
    }
    return x;
}

Upvotes: 1

Related Questions