使用atoi()将argv []转换为整数,将整数分配给另一个函数要使用的目标

时间:2019-03-01 12:23:25

标签: c arrays function pointers atoi

我正在尝试编写一个名为command_to_integer_array的函数。在此函数中,我想将命令行参数数组转换为整数并将整数存储在整数数组中。

函数的返回值为destination,将整数复制到(int*)的位置。

输入为source,是要从(char **)复制的源位置,而length是要复制的整数(int

示例:
如果argv[1] = "20"argv[2] = "50"argv[3] = "80",则 length = 3,返回的整数数组应为destination[0] = 20destination[1] = 50destination[2] = 80

编译以下代码时,出现assignment to expression with array type错误。

如何从此函数返回整数数组?

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

int *command_to_integer_array(char** source, int length);

int main(int argc, char *argv[])
{
  int length = 0;
  char *data;

  // check if in the range of 1 and 10 argcs
  if( argc > 11 || argc < 2 ) {
    printf("Arguments 1 through 10 required %d provided\n", argc-1);
    exit(EXIT_FAILURE);
  }

  //get the command line arguments count and store into length 
  length = argc-1;

  //allocate memory on the heap for the users input 
  data = malloc((argc - 1) * sizeof *data);

  //copy the Command line arguments input onto the heap
  command_to_integer_array(&data, length);

  // call the average function using arguments float average(int *numbers, int length);
  // printf("The average is %f\n", average());

  puts(data);
  free(data);

  return 0;
}

int *command_to_integer_array(char** source, int length)
{
  //convert each argv[] to an integer using atoi() and assign the integer to the destination.
  int vals[length];
  int *destination;
  for (int i = 0; i < length; ++i)
  {
     vals = atoi(source[i]);     
  }  

  destination = vals;
  return destination;

} 

0 个答案:

没有答案