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 characterwhich 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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.