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()
'.