将'integer strings'转换为integer array

时间:2021-06-18 15:59:24

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

2 个解决方案

#1


3  

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.

假设argc和argv是传递给main的参数,那么argv[0]不太可能是您想要转换成整数的东西。argv[0]通常包含程序的名称。

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


2  

You are declaring your array arr every time you loop.

每次循环时都声明数组arr。

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

#1


3  

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.

假设argc和argv是传递给main的参数,那么argv[0]不太可能是您想要转换成整数的东西。argv[0]通常包含程序的名称。

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


2  

You are declaring your array arr every time you loop.

每次循环时都声明数组arr。

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