I have a char* formatted like:
* SEARCH 1 2 3 ...
with a variable number of integers separated by spaces. I would like to write a function to return an int[] with the integers after * SEARCH.
How should I go about writing this function?
I have a char* formatted like:
* SEARCH 1 2 3 ...
with a variable number of integers separated by spaces. I would like to write a function to return an int[] with the integers after * SEARCH.
How should I go about writing this function?
 
    
    #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int *f(const char *s, int *n /* out */){
    if(strncmp(s, "* SEARCH", 8)!=0){
        fprintf(stderr, "format error!\n");
        *n = 0;
        return NULL;
    }
    s += 8;
    const char *p = s;
    int v, len, status;
    int count = 0;
    while((status=sscanf(p, "%d%n", &v, &len))==1){
        ++count;
        p +=len;
    }
    if(status==0){
        fprintf(stderr, "format error!\n");
        *n = 0;
        return NULL;
    }
    int *ret = malloc(count * sizeof(*ret));
    p = s;
    count = 0;
    while(EOF!=sscanf(p, "%d%n", &v, &len)){
        ret[count++]=v;
        p +=len;
    }
    *n = count;
    return ret;
}
int main (void){
    int i, n, *nums = f("* SEARCH 1 2 3", &n);
    for(i=0; i<n; ++i)
        printf("%d ", nums[i]);
    printf("\n");
    free(nums);
    return 0;
}
