Buddy
Buddy

Reputation: 13

Allocate array from command line parameters

I am working on a small C application and I am capturing a value from the command line. I would like to capture the value and use it to initialize an array. Here is what I'm trying to do.

int main(int argc, char* argv[]) {
    int option = atoi(argv[2]);
    int values[option];
    ......
 }

I am getting a compilation because my option variable is not a const. Error: Error 2 error C2057: expected constant expression

Is there a way I can do this?

Thanks for your help!

Upvotes: 1

Views: 1586

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 754050

If your compiler supports C99, then (if you don't mind living slightly dangerously, given that there is no check that argv[2] is defined or that the value in it can be converted to a sane positive integer), you can write:

#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
    int option = atoi(argv[2]);
    char *values[option];
    int i;
    int n = argc - 3;
    for (i = 0; i < n; i++)
        values[i] = argv[i+3];

    for (i = 0; i < n; i++)
        printf("values[%d] = %s\n", i, values[i]);
    return 0;
}

This compiles and runs, using the C99 VLA (variable-length array) feature. Note I changed the type of 'values' to a 'char *', mainly for laziness - to get something done.

The warning message looks like it comes from MSVC, and MSVC 2010 still does not support many of the extra features added to C99. For that environment, therefore, you will have to fall back onto memory allocation:

#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
    int option = atoi(argv[2]);
    char **values = malloc(option * sizeof(*values));
    int i;
    int n = argc - 3;
    for (i = 0; i < n; i++)
        values[i] = argv[i+3];

    for (i = 0; i < n; i++)
        printf("values[%d] = %s\n", i, values[i]);

    free(values);
    return 0;
}

Subtle point to note: the operand to 'sizeof' is '*values', which will remain correctly sized even if you change the type of 'values' from 'char **' back to 'int *' as in your outline. If I'd written 'sizeof(char *)', then you'd have to change two things - the declaration of 'values' and the type name in 'sizeof()'.

Upvotes: 1

Tyler McHenry
Tyler McHenry

Reputation: 76680

If the size is not known at compile-time, you need to allocate the memory dynamically, with malloc:

 int main(int argc, char* argv[]) {
    int option = atoi(argv[2]);
    int* values = malloc(option * sizeof(int));
    /* ...... */
    free(values); /* Deallocate the memory when you are done with it */
 }

Upvotes: 8

Related Questions