A function with the signature implied in your post is not possible in C, because a function cannot return a dynamically-sized array. Two choices are possible here:
- Pass an array and the max count into
parseString
, or
- Return a pointer representing a dynamically allocated array, along with its actual size.
The first approach limits the size of the array to some number established by the caller; the second approach comes with a requirement to deallocate the array once you are done with it.
The function that follows the first approach would look like this:
void parseString(int data[], size_t maxSize);
The function that follows the second approach would look like this:
int *parseString(size_t *actualSize);
or like this:
void parseString(int ** data, size_t *actualSize);
The second case can be used to combine the two approaches, although the API would become somewhat less intuitive.
As for the parsing itself, many options exist. One of the "lightweight" options is using strtol
, like this:
char *end = str;
while(*end) {
int n = strtol(str, &end, 10);
printf("%d\n", n);
while (*end == ',') {
end++;
}
str = end;
}
Demo.