I am trying to tokenize a string to give an array of strings but it seems like my code is wrong.
Here is my code:
asmInstruction *tokenizeLine(char *charLine) {
int words = countTokens(charLine);
char *tokens = (char*) malloc(MAX_LINE_LENGTH);
asmInstruction *instr = (asmInstruction*) malloc(sizeof(asmInstruction*));
instr->args = (char**) malloc(MAX_LINE_LENGTH);
int count = 1;
tokens = strtok(charLine, " ,");
while (count <= words) {
tokens = strtok(NULL, " ,");
instr->args[count - 1] = (char*)malloc(MAX_LINE_LENGTH);
instr->args[count - 1] = tokens;
++count;
}
free(tokens);
return instr;
}
/* Reads a file and returns the number of lines in this file. */
uint32_t countLines(FILE *file) {
uint32_t lines = 0;
int32_t c;
while (EOF != (c = fgetc(file))) {
if (c == '\n') {
++lines;
}
}
/* Reset the file pointer to the start of the file */
rewind(file);
return lines;
}
And the structure:
typedef struct {
char **args; /* An array of strings*/
} asmInstruction;
My main is here:
int main() {
char s[] = "ldr r2,r1";
asmInstruction *instr = tokenizeLine(s);
printf("%s", instr->args[0]);
}
/* Counts the number of tokens in a line */
uint32_t countTokens(char line[]) {
/* The correct way to do this! */
uint32_t numberOfTokens = 0;
/* Split at spaces and commas */
char *tokens = strtok(line, " ,");
while (tokens != NULL) {
tokens = strtok(NULL, " ,");
numberOfTokens++;
}
return numberOfTokens;
}
So, this should print ldr. However, it prints null. If I loop over the tokens it doesn't print them out but null. I'm expecting to print out the tokens
ldr r2 r1
But only the first one gets printed out.
It seems like instr->args[count-1]
never gets assigned something because apparently tokens
hasn't been assigned something either.
Why is that? Thanks.