Static or Pointer When "Returning" Array

InfoSecNick

I'm attempting to load an array of size n (user input), with random values. I've read that you can not return an array in C, you must use a pointer (Which is quite confusing). However, I've read that if you are storing that array to a local variable in the returning function, a pointer will not work and a static array can be used (can that be returned in a function?). Also, I've read that you are supposed to call free after using the array is open the space back up? I must be using it wrong because it crashed. So I commented it out for now. Some clarification would be great.

Here's what I have so far. When printing, it's just printing what I'm assuming is just garbage.

int* prefixAverages1(int);

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main() {

    int choice;
    int input;

    printf("What is the size of the array?:");
    scanf("%d", &input);
    printf("Do you want to run prefixAverages 1 or 2?");
    scanf("%d", &choice);

    switch(choice) {
        case 1:
            printf("Beginning prefixAverages1\n");
            int *a = prefixAverages1(input);
            for (int i=0; i < input; i++) {
                printf("%d", &i);
                printf("%d \n", a[i]);
            }
            //free(a);
            break;
    }
}

int* prefixAverages1(int input) {
    int x[input];
    int *a = (int*)malloc(input);
    srand(time(NULL));  

    for(int i = 0; i < input; i++) {
        int s = 0;
        for(int j = 0; j < i; j++) {
            int r = rand() % 100;
            x[j] = r;
            s = s + x[j];
        }
        a[i] = s / (i+1);
        printf("%d \n", a[i]);
    }
    return a;
}

I'm aware my syntax may be wonky. I haven't touched C in years, so let me know if my error is syntaxical.

edit: Values are printing as intended in the function. Added print statement in code for clairity

John Bollinger

I'm attempting to load an array of size n (user input), with random values. I've read that you can not return an array in C, you must use a pointer (Which is quite confusing).

Yes, the relationship between pointers and arrays and the surprisingly wide scope of things you cannot do with arrays themselves are common points of confusion. To some extent it's a pedantic distinction. Almost everything C allows you to do with an array, it makes you do via a pointer, but it automatically converts values of array type to appropriate pointers, so that those details are largely hidden.

But in some places it pokes out. For example, there is no valid syntax that allows you even to try to declare a function that returns an array.

In other places it is actively misleading. For example, you can declare a function that appears to accept an array as an argument, but the standard explicitly specifies that the argument is actually a corresponding pointer (and that's what naturally falls out when you call such a function anyway). Specifically:

int foo(int x[3]);

is 100% equivalent to

int foo(int *x);

However, I've read that if you are storing that array to a local variable in the returning function, a pointer will not work

That's not so much about arrays specifically, but rather about automatic variables in general. These logically cease to exist when they go out of scope -- at the end of the innermost block in which they are declared -- so pointers to or into such objects are no longer valid once the function returns. One way to obtain such a pointer value is for the function to return it. That in itself is OK, but you cannot safely dereference such a pointer value.

and a static array can be used (can that be returned in a function?).

The lifetime of static variables of any type is the whole execution of the program. Therefore, it is safe and can be meaningful to return a pointer (in)to a static variable from a function. But although it can work to return a pointer to a static array from your function, you still cannot return such an array itself.

Also, I've read that you are supposed to call free after using the array is open the space back up?

You should free memory that you have allocated with one of the memory allocation functions (malloc() etc.), and no other. But when you allocate memory inside a function, you can give the caller responsibility for freeing that memory by returning the pointer to it, among other ways.

In fact, most of what you demonstrate in your example code is fine in those regards. However, you do make a key error that undermines your program. Here:

    int *a = (int*)malloc(input);

You allocate input bytes and store the pointer to them in a, but that is not enough storage for input objects of type int. The size of an int varies from implementation to implementation, but the minimum size permitted by the standard is two bytes, in the most common size is four bytes. To allocate space for input objects of type int, the basic idiom is

int *a = malloc(input * sizeof(int));

Personally, though, I prefer

int *a = malloc(input * sizeof(*a));

because then I get the correct size no matter what type the pointer's referenced type is, and even if I change it later.

The fact that you treated the allocated space as if it were larger than it really was likely explains much of your program's misbehavior, including the crash when you tried to free the allocated memory.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to return a static array pointer

Stack behavior when returning a pointer to local variable

When use malloc for a static pointer inside a function?

Returning pointer to static (outside function) array

Returning a pointer to an array

Returning pointer to statically defined array of structs

C++, static array, pointer, length

Returning a pointer to an array of structs

Possible memory leak when returning pointer (array) (C++)

Cast static array to pointer in Delphi?

Returning a pointer to a char array inside a struct in C?

Why is there a difference when assigning an array with static keyword and without to a pointer?

Returning a function's static array to another array in the main() function

Returning Pointer to Bidimensional Array [C++]

Returning a pointer to an array C++

mysql_fetch_array returning false when pointer is at exactly 1/2 of mysql_num_rows

Returning an array as a pointer

When querying Parse pointer -- it is returning nil

returning static pointer to local variable from function

function returning pointer vs function returning array in C

function returning array as an pointer

Static array initialization with pointer to extern struct element?

initialize static pointer array c++

Why is it needed to declare an array as static when returning it from a function. (C++)

Static Inner class returning null when instantiating

Returning result via pointer to array

Returning a struct containing a pointer to the first element of an array

I'm puzzled with the pointer arithmetic on a static array

Returning a static cast to a pointer doesn't return a pointer C++