繁体   English   中英

转换命令行参数数组并将其存储在int数组中

[英]Convert an array of command line arguments and store them in an int array

我正在编写一个程序,该程序从命令行(例如10 20 30 40)获取参数数组,将其转换为整数,然后将其保存在int数组中,以备后用。 我已经声明了堆的指针。 我想将CL中的数字计数存储在length变量中。 然后为该长度分配空间,并将其复制到堆中。 接下来,使用一个将命令行参数转换为整数并将其复制到int数组中的函数,我对如何传递命令行值感到困惑。 有人可以指出我正确的方向吗? 谢谢。

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

void convert(char** source, int length);

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

  int length = 0;
  char *p_heap;

  if( argc > 11 || argc < 2 ) {
    printf("arguments 1-10 are accepted %d provided\n", argc-1);
    printf("Program Name Is: %s",argv[0]); 
    exit(EXIT_FAILURE);
  }

  length = argc-1;
  p_heap = malloc(sizeof(length));
  strcpy(p_heap, length);
  convert(p_heap, length);

  //printf("Average %f\n", avg());

  puts(p_heap);
  free(p_heap);

  return 0;
}

void convert(char** source, int length){

  int *dst;
  int i;

  for(i=0;i<length;i++) {
    dst = atoi([i]); 
  } 


}

注意:我假设来自CL的正确输入。

我想将CL中的数字计数存储在length变量中。

如果您假设来自CL的输入正确,那么您在argc-1拥有此数字。

然后为该长度分配空间,并将其复制到堆中。

dst = malloc((argc-1)*sizeof *dst);

接下来,使用将命令行参数转换为整数并将其复制到int数组中的函数。

for(int i=0; i<argc-1; i++) 
    sscanf(source[i], "%d", &dst[i]);

您还应该convert的返回类型更改为int * ,然后返回dst

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

int main(int argc, char **argv)
{
    if (argc == 1)
        return EXIT_SUCCESS;

    long *data = malloc((argc - 1) * sizeof *data);

    for (int i = 1; i < argc; ++i) {
        char *endptr;

        errno = 0;
        data[i-1] = strtol(argv[i], &endptr, 10);

        if (*endptr != '\0') {
            fputs("Input error :(", stderr);
            return EXIT_FAILURE;
        }

        if (errno == ERANGE) {
            fputs("Parameter out of range :(\n\n", stderr);
            return EXIT_FAILURE;
        }
    }

    for (int i = 0; i < argc - 1; ++i)
        printf("%ld\n", data[i]);

    free(data);
}

为什么在if( argc > 11 || argc < 2 ) {与11进行比较?

 length = argc-1; p_heap = malloc(sizeof(length)); 

sizeof(length)sizeof(int) ,如果您希望的话,它不取决于length的值

strcpy(p_heap,长度);

strcpy获得两个char*长度值是args的数目,而不是char数组的地址,因此结果是不确定的,并且可能很戏剧性

 convert(p_heap, length); 

convert的第一个参数必须为char**p_heapchar*

 void convert(char** source, int length){ int *dst; int i; for(i=0;i<length;i++) { dst = atoi([i]); } 

}

你不使用

dstint*atoi返回int

[i] ???

在提供SO代码之前,我建议您先使用高警告级别(例如gcc -pedantic -Wextra for gcc )检查它的编译是否没有警告/错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM