我正在为一个简单的汇编器做一个作业,它应该像高级编程语言一样识别任意变量名称。我尝试对 char 指针数组使用动态分配
我只是想创建一个可扩展的字符串数组,并能够在该数组中搜索特定字符串,但它在尝试比较两个字符串时出现分段错误 [行:14]
Comp(&buffer[1], Variables[i];
Run Code Online (Sandbox Code Playgroud)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define Comp(a,b) strcmp(a,b) == 0 ? 1 : 0
char buffer[255], **Variables;
int VariableIndex;
void A_instructionHandler() {
int A_Operand, test = 0;
if (buffer[0]== '@') {
for (int i = 0; i <= VariableIndex; i++) {
test = Comp(&buffer[1], Variables[i]);
if (test) {
A_Operand = i + 16;
break;
}
}
}
}
int main(int argumentCounter, char *arguments[]) {
strcpy(buffer, "@variable");
Variables = (char **)calloc(VariableIndex + 1, sizeof(char**));
A_instructionHandler();
}
Run Code Online (Sandbox Code Playgroud)
下面是将代码重构为更惯用的内容:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void instruction_handler(char* buffer, char** variables) {
switch (buffer[0]) {
case '@':
// This iterates over the NULL terminated array by stopping when
// it hits a NULL pointer, or in other words *v is false.
for (char **v = variables; *v; ++v) {
// If this matches a variable name...
if (!strcmp(*v, &buffer[1])) {
// Variable matched, so show some debugging code
printf("Found variable: %s\n", *v);
return;
}
}
}
}
int main(int argc, char* argv[] ) {
// Create a simple NULL-terminated array of arbitrary size
char *variables[] = {
"variable",
NULL
};
instruction_handler("@variable", variables);
}
Run Code Online (Sandbox Code Playgroud)
variables只要 NULL 终止符保留在末尾,就可以按照您喜欢的方式定义该数组、扩展、缩小。
基于您的原始代码的一些提示:
strcmp()处理它是多么奇怪,不要将其包装在 a 中#define并发明你自己的没人理解的 C 方言。随着时间的推移,你会习惯 C,它不会给你带来太大的困扰,而且你可以编写代码,而不会让团队中的其他人感到厌烦。argc像扩展为这样的解释argumentCounter最好用注释来表达,而不是一个尴尬的长变量名,尤其是非常不标准的变量名。评论很棒。尽可能多地使用它们!