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

标签 c arrays parsing char int

我有一个如下所示的字符数组:

[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);

}

最佳答案

给定发布的代码,该代码无法编译:

    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. 它只分配一个字符,而不管每个数组条目中的实际字符数。
  2. 它不会生成整数数组。
  3. 无法获取多个角色

我们可以通过以下方式解决其中一些问题:

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

这将导致:

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()

的函数

关于在 C 中将 char 数组转换为整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33898441/

相关文章:

c - C 中 strtok 的段错误

javascript - 在 javascript 中创建简单过滤器函数的最佳方法是什么?

c++动态二维数组不使用默认构造函数

javascript - 当您迭代对象数组并且对象属性是逗号分隔的字符串时,有没有一种好的方法可以进行比较?

ruby - 从 Ruby 中的字符串解析十进制值

java - 如何在 Java 中解析 HTML 字符串?

c - 使用功能指针方法进行状态机设计的三选二投票

c - 来自 GetRawInputDeviceList() 的原始输入设备太多

c - struct内存分配,内存分配应该是4的倍数

c++ - 在 C++ 中验证 GPS 字符串的最简单方法?