简体   繁体   中英

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:

  1. it only allocates a single char, regardless of actual number of characters in each array entry.
  2. It does not produce an array of integers.
  3. there is no way to acquire multiple characters

We could address some of these problems by:

  1. modifying the function: proc.read() to return a pointer to a NUL terminated char string rather than just a single character
  2. converting that char string to an integer
  3. allocating enough new memory at each iteration to hold an integer

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM