[英]Convert char array into an array of integers in C
I have a char array like the following one:我有一个像下面这样的字符数组:
[0, 10, 20, 30, 670]
How can I convert this string into an array of integer?如何将此字符串转换为整数数组?
This is my array这是我的数组
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);
}
given the posted code, which does not compile:鉴于发布的代码,它不会编译:
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);
}
it can be turned into a compilable function by:它可以通过以下方式变成一个可编译的函数:
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);
}
}
then re-arranged to eliminate unnecessary calls to system functions and adding error checking:然后重新安排以消除对系统函数的不必要调用并添加错误检查:
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
The above has some problems:上面有一些问题:
We could address some of these problems by:我们可以通过以下方式解决其中一些问题:
proc.read()
to return a pointer to a NUL terminated char string rather than just a single characterproc.read()
返回指向 NUL 终止的字符字符串的指针,而不仅仅是单个字符which would result in:这将导致:
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
however, there are still some problems.然而,仍然存在一些问题。 Specifically a C program cannot have functions named:
proc.available()
nor proc.read()
具体来说,C 程序不能有名为:
proc.available()
或proc.read()
函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.