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

Time:01-31

Suppose that we have

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

Is it possible to initialise arr with str?

CodePudding user response:

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.

CodePudding user response:

You can't do that specifically, statically, but you can kind of do the reverse.

You can create a "to string" macro like this:

#define __STR(x) #x
#define STR(x) __STR(x)

Then you can use it like this:

#define NUMS {10,20,30}
int arr[3] = NUMS;
char str[] = STR(NUMS); 
  •  Tags:  
  • c
  • Related