'There is an error in that line --> `char ** tokenizer(char *line, int& noOfTokens) ` --- Can you help me?

There is an error in that line:

char **tokenizer(char *line, int& noOfTokens)
the error is -->[Error] expected ';', ',' or ')' before '&' token

char **tokenizer(char *line, int& noOfTokens) {
    char **tokens = (char **)malloc(10 * sizeof(char *));
    char *token = (char *)malloc(10 * sizeof(char));
    int k = 0;
    token[0] = '\0';
    int i = 0;
    while (line[i] == ' ')
        i++;
    for (; line[i] != '\n' && line[i] != '\0'; i++) {
        if (line[i] == ' ' || line[i] == ',' || line[i] == '[' || line[i] == ']' || line[i] == '\t') {
            if (token[0]!='\0') {
                token[k] = '\0';
                tokens[noOfTokens++] = token;
                token = (char *)malloc(10 * sizeof(char));
                token[0]='\0';
                k = 0;
            } else
                continue;
        } else {
            token[k++] = line[i];
        }
    }
    if (token[0] != '\0') {
        token[k] = '\0';
        tokens[noOfTokens++] = token;
    }
    return tokens;
}
c


Solution 1:[1]

There is no passing by reference in C. You must pass the address of the number of tokens for the function to update it.'

You also have memory leaks and potential buffer overflows if a token has more than 9 bytes.

Here is a modified version:

#include <stdlib.h>
#include <string.h>

char **tokenizer(const char *line, int *noOfTokens) {
    char **tokens = NULL;
    int i = 0;  // index into the string
    int k = 0;  // number of tokens
    int n;      // token length

    for (;;) {
        // skip whitespace
        while (line[i] == ' ' || line[i] == '\t')
            i++;
        // check for end of line
        if (line[i] == '\0' || line[i] == '\n')
            break;
        // test 1 byte tokens
        if (line[i] == ',' || line[i] == '[' || line[i] == ']') {
            n = 1;
        } else {
            // find token length
            n = strcspn(line + i, " \t\n,[]");
        }
        tokens = realloc(tokens, (k + 1) * sizeof(*tokens));
        tokens[k++] = strndup(line + i, n);
        i += n;
    }
    *noOfTokens = k;
    return tokens;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chqrlie