将char数组转换为C中的整数数组

时间:2015-11-24 16:06:20

标签: c arrays parsing char int

我有一个像以下一样的char数组:

[0, 10, 20, 30, 670]

如何将此字符串转换为整数数组?

这是我的数组

int i=0;
size_t dim = 1;
char* array = (char*)malloc(dim);

while (proc.available()){

  array[i] = (char)proc.read();
  dim++;
  i++;
  array = (char*)realloc(array,dim);

}

1 个答案:

答案 0 :(得分:1)

给出已发布的代码,但不编译:

    int i=0;
    size_t dim = 1;
    char* array = (char*)malloc(dim);

    while (proc.available()){

    array[i] = (char)proc.read();
    dim++;
    i++;
    array = (char*)realloc(array,dim);

}

它可以通过以下方式变成可编辑的功能:

void allocateArray()
{
    int i=0;
    size_t dim = 1;
    char* array = (char*)malloc(dim);

    while (proc.available())
    {

        array[i] = (char)proc.read();
        dim++;
        i++;
        array = (char*)realloc(array,dim);
    }
}

然后重新安排以消除对系统功能的不必要调用并添加错误检查:

char * allocateArray()
{
    int i=0;
    size_t dim = 1;
    char* array = NULL;

    while (proc.available())
    {
        char *temp = realloc(array,dim);
        if( NULL == temp )
        {
            perror( "realloc failed" );
            free( array );
            exit( EXIT_FAILURE );
        }

        // implied else, malloc successful

        array[i] = (char)proc.read();
        dim++;
        i++;
    }
    return array;
} // end function: allocateArray

以上有一些问题:

  1. 它只分配一个char,而不管每个数组条目中的实际字符数。
  2. 它不会产生整数数组。
  3. 无法获取多个字符
  4. 我们可以通过以下方式解决其中一些问题:

    1. 修改函数:proc.read()返回指向NUL的指针 终止字符串而不是单个字符
    2. 将该字符串转换为整数
    3. 在每次迭代时分配足够的新内存以保存整数
    4. 会导致:

      int * allocateArray()
      {
          int i=0;
          size_t dim = 1;
          int* array = NULL;
      
          while (proc.available())
          {
              int *temp = realloc(array,dim*sizeof(int));
              if( NULL == temp )
              {
                  perror( "realloc failed" );
                  free( array );
                  exit( EXIT_FAILURE );
              }
      
              // implied else, malloc successful
      
              array = temp;
              array[i] = atoi(proc.read());
              dim++;
              i++;
          }
          return array;
      } // end function: allocateArray
      
      然而,仍然存在一些问题。具体而言,C程序不能具有名为proc.available()proc.read()

      的函数