我有一个如下所示的字符数组:
[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
上面有一些问题:
- 它只分配一个字符,而不管每个数组条目中的实际字符数。
- 它不会生成整数数组。
- 无法获取多个角色
我们可以通过以下方式解决其中一些问题:
- 修改函数:
proc.read()
以返回指向 NUL 的指针 终止的字符串而不是单个字符 - 将该字符串转换为整数
- 在每次迭代时分配足够的新内存来保存整数
这将导致:
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/