Converting 'integer strings' to integer array

半城伤御伤魂 提交于 2019-12-02 03:37:44

问题


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]);
}

回答1:


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]);
}



回答2:


You are declaring your array arr every time you loop.

change your loop like this:

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

int main(int argc, char *argv[])
{

    int arr[argc];
    int i=0;


    for(i = 0; i < argc-1; i++)
    {
       arr[i] = atoi(argv[i+1]);
       printf("arr[%d] = %d\n",i,arr[i]);
    }

    return 0;
}

Here is the output:

Sukhvir@Sukhvir-PC ~
$ gcc -Werror -Wall -g -o test test.c

Sukhvir@Sukhvir-PC ~
$ ./test 3 4 5
arr[0] = 3
arr[1] = 4
arr[2] = 5


来源:https://stackoverflow.com/questions/19473439/converting-integer-strings-to-integer-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!