在我开始之前,这是导致我出现问题的代码块。
typedef struct SymbPair{
char *symbol;
int memoryAddress;
}SymbPair;
typedef struct SymbTable{
SymbPair *pairs;
int numberOfItems;
} SymbTable;
SymbTable createTable(){
SymbTable table;
table.pairs = (SymbPair*) calloc(1,sizeof(SymbPair));
table.numberOfItems = 0;
return table;
}
int checkForColon(char *word){
if (word[strlen(word) - 1] == ':'){
return 1;
} else {
return 0;
}
}
void removeLastChar(char *word, char *buffer){
int size = strlen(word);
char blank[size - 1];
for (int i = 0; i < size - 1; i++){
blank[i] = word[i];
}
blank[size - 1] = '\0';
strcpy(buffer,blank);
}
void symbPairSet(char *word, int address, SymbPair *pair){
pair -> memoryAddress = address;
pair -> symbol = word;
}
void addToSymbTable(SymbPair sp, SymbTable *array){
int currentTotal = array->numberOfItems;
array -> pairs = (SymbPair*) realloc(array->pairs,currentTotal+2);
array->pairs[currentTotal]=sp;
array -> numberOfItems = currentTotal + 1;
}
void firstPass(SymbTable *table, char **instructions){
int totalLabels = 0;
int i = 0;
while (instructions[i] != NULL){
if (checkForColon(instructions[i])){
char buffer[strlen(instructions[i]) - 1];
removeLastChar(instructions[i],buffer);
SymbPair new;
symbPairSet(buffer,(i*4) - totalLabels,&new);
addToSymbTable(new,table);
totalLabels++;
}
i++;
}
}
int main(){
SymbTable table = createTable();
firstPass(&table,instructionArray);
return EXIT_SUCCESS;
}
第一次传入字符串数组并查找以冒号结尾的字符串,然后删除冒号并将编辑后的字符串添加到符号对数组中,该数组保存在包含数组及其大小的结构调用符号表中。使用我当前的输入,数组中应该有一个带有符号循环和地址 8 的项目。我的问题是,在 firstPass 函数中,字符串具有正确的值,但是一旦它被传递到 main 中的值,它就会完全改变。符号(或字符串)的值从 firstPass 函数内部更改为在 main 中分配时,但它应该是相同的。有什么帮助吗?