我有一些 C 代码来解析文本文件,首先逐行解析,然后解析为令牌
这是逐行解析它的函数:
int parseFile(char *filename) {
//Open file
FILE *file = fopen(filename, "r");
//Line, max is 200 chars
int pos = 0;
while (!feof(file)) {
char *line = (char*) malloc(200*sizeof(char));
//Get line
line = fgets(line, 200, file);
line = removeNewLine(line);
//Parse line into instruction
Instruction *instr = malloc(sizeof(instr));
instr = parseInstruction(line, instr);
//Print for clarification
printf("%i: Instr is %s arg1 is %s arg2 is %s\n",
pos,
instr->instr,
instr->arg1,
instr->arg2);
//Add to end of instruction list
addInstruction(instr, pos);
pos++;
//Free line
free(line);
}
return 0;
}
这是将每一行解析为一些标记并最终将其放入指令结构的函数:
Instruction *parseInstruction(char line[], Instruction *instr) {
//Parse instruction and 2 arguments
char *tok = (char*) malloc(sizeof(tok));
tok = strtok(line, " ");
printf("Line at %i tok at %i\n", (int) line, (int) tok);
instr->instr = tok;
tok = strtok(NULL, " ");
if (tok) {
instr->arg1 = tok;
tok = strtok(NULL, " ");
if(tok) {
instr->arg2 = tok;
}
}
return instr;
}
ParseInstruction 中的行printf("Line at %i tok at %i\n", (int) line, (int) tok);
总是打印相同的两个值,为什么这些指针地址永远不会改变?我已经确认 parseInstruction 每次都返回一个唯一的指针值,但是每条指令的 instr 槽中都有相同的指针。
为清楚起见,指令定义如下:
typedef struct Instruction {
char *instr;
char *arg1;
char *arg2;
} 操作说明;
我究竟做错了什么?