Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to initialise array of integers with string?

Suppose that we have

int arr[3]; 
char str[20] = "{10,20,30}"; 

Is it possible to initialise arr with str?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Not statically, you would need to parse the string and then assign the parsed values to arr.

You can parse numbers (and more) from strings with sscanf or with strtol (just parsing integers).

One way to parse {10,20,30} could be:

#include <stdio.h>
#include <string.h>

int main(void) {
    int arr[3] = {0};
    int pos = 0;

    char str[20] = "{10,20,30}"; 

    // str + 1: skip the first character '{'
    char *token = strtok(str + 1, ",");

    while (token) {
        int tmp = 0;

        // check if the parsing was actually successful
        if (sscanf(token, "%d", &tmp) == 1) {
            // a good program would check if 'pos' is within 
            // proper range of 'arr', in the case of arr[3]: 
            // acceptable range: 0-2
            arr[pos] = tmp;

            ++pos;
        }

        // get the next token
        token = strtok(NULL, ",");
    }

    for (int i = 0; i < sizeof(arr) / sizeof(* arr); ++i) {
        printf("arr[%d] = %d\n", i, arr[i]);
    }
}

This is very rudimentary it lacks proper handling of the {} braces and strtok IS NOT able to process more than one string at a time. A better solution would use strtok_r.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading