Converting 'integer strings' to integer array

Brian Maher picture Brian Maher · Oct 20, 2013 · Viewed 11.9k times · Source

I'm trying to pass in an array of integers into my program. Is there a better way to convert it to integers? I'm currently getting an error: "Variable sized object may not be initialized"

for(i = 0; i < argc; i++)
{
    int arr[i] = atoi(argv[i]);
}

Answer

jxh picture jxh · Oct 20, 2013

Assuming argc and argv are the arguments passed to main, it is unlikely that argv[0] is something that you want to convert into an integer. argv[0] usually contains the name of the program.

Your code snippet is declaring an array local to the loop body. What you likely want is an array defined outside the loop body, and you want to assign to individual array elements within the loop body.

int arr[argc];
for(i = 1; i < argc; i++)
{
    arr[i] = atoi(argv[i]);
}