我正在为一个简单的汇编程序进行分配,该汇编程序应识别诸如高级编程语言之类的任意变量名。我试图使用动态分配到char指针数组
我只是想制作一个可扩展的字符串数组,并且能够在该数组中搜索特定的字符串,但是在尝试比较两个字符串的过程中却出现了分段错误[line:14]
Comp(&buffer[1], Variables[i];
#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();
}
这是将代码重构为更惯用的代码:
#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);
}
variables
只要NULL终止符保留在最后,您就可以在哪里定义,扩展,缩小该数组的位置。
根据原始代码的一些提示:
strcmp()
并处理它的怪异之处,不要将其包装在a中#define
并发明自己的C方言,没人能理解。随着时间的流逝,您会逐渐习惯C语言,它不会给您带来太多麻烦,并且您可以在不驱使团队中其他人陷入困境的情况下进行编码。argc
扩展到之类的解释argumentCounter
最好用注释来表示。评论很棒。尽可能多地使用它们!本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句