Skip to content

Instantly share code, notes, and snippets.

@jarhill0
Last active May 9, 2018 18:12
Show Gist options
  • Save jarhill0/3927881d383f7f22790705427073227a to your computer and use it in GitHub Desktop.
Save jarhill0/3927881d383f7f22790705427073227a to your computer and use it in GitHub Desktop.

So I want to return an array in C of length determined at runtime.

This is what I tried at first:

#include <stdio.h>

void printArray(int array[], int length) {
    for (int i = 0; i < length; i++)
        printf("%d", *(array + i));
    printf("\n");
}

int* arrayOfLength(int length) {
    int array[length];
    for (int i = 0; i < length; i++)
        array[i] = i + 1;
    return array;
}

int main() {
    int length = 5;
    int* array = arrayOfLength(length);
    printArray(array, length);
    return 0;
}

This unfortunately doesn't compile:

$ clang -o returnarray returnarray.c 
returnarray.c:13:12: warning: address of stack memory associated with local
      variable 'array' returned [-Wreturn-stack-address]
    return array;
           ^~~~~
1 warning generated.

Ah, I see, it's useless to return a pointer to a local variable, because that's about to go out of scope. I'll try making that static.

int* arrayOfLength(int length) {
    static int array[length];
    for (int i = 0; i < length; i++)
        array[i] = i + 1;
    return array;
}

Now try to compile:

$ clang -o returnarray returnarray.c 
returnarray.c:10:16: error: variable length array declaration cannot have
      'static' storage duration
    static int array[length];
               ^     ~~~~~~
1 error generated.

Huh. Search up that error and stumble across a StackOverflow answer. Let's edit our function again.

int* arrayOfLength(int length) {
    static int* array;
    array = (int*) malloc(length * sizeof(int));
    for (int i = 0; i < length; i++)
        array[i] = i + 1;
    return array;
}

I get an error about needing to include the standard library. I include that, and it compiles! I don't really know how to use malloc, but I guess this is my introduction…

Now let's run the final program.

$ ./returnarray 
12345

Hoorah!


The final program:

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

void printArray(int array[], int length) {
    for (int i = 0; i < length; i++)
        printf("%d", *(array + i));
    printf("\n");
}

int* arrayOfLength(int length) {
    static int* array;
    array = (int*) malloc(length * sizeof(int));
    for (int i = 0; i < length; i++)
        array[i] = i + 1;
    return array;
}

int main() {
    int length = 5;
    int* array = arrayOfLength(length);
    printArray(array, length);
    return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment