【发布时间】:2016-03-14 00:03:12
【问题描述】:
我在尝试将指针用作另一个函数内的函数的参数时遇到了一些麻烦。我的目标是在每个函数中保留变量“counter”的值,换句话说,当最低的函数声明一个“counter++”时,它的值必须为程序中的每个其他“counter”变量递增。
我的代码如下所示:
int main(int argc, const char * argv[]) {
Hash tableHash;
char command[6];
int id = 0, counter = -1;
int flags[4] = {0, 0, 0, 0};
while(1) {
identifyCommand(command, id, &tableHash, flags, &counter);
}
return 0;
}
在我的 .h 中:
void identifyCommand(char* command, int id, Hash* tableHash, int* flag, int* counter){
scanf("%s", command);
/* ... */
if(strcmp(command, "INSERT") == 0){
scanf("%i", &id);
commandInsert(id, tableHash, counter, flag);
}
/* ... */
return;
}
void commandInsert(int id, Hash* tableHash, int* counter, int* flag){
Registry x;
x.key = id;
if(flag[MALLOCFLAG]){
tableHash->trees[*counter] = create_tree(x);
counter++;
flag[MALLOCFLAG] = 0;
}
else {
insert_element(tableHash->trees[*counter], x);
}
return;
}
我的主要问题是:当我运行代码时,即使在 commandInsert() 函数中运行了“counter++”命令后,它也会继续发送计数器的“-1”值。为什么会发生这种情况,我该如何解决?
我认为问题可能出在 commandInsert(id, tableHash, counter, flag) 调用上,因为我没有使用参考符号 (&),但是在 identifyCommand() 内部时,'counter' 已经是一个指针,因为它的参数,所以我在这里缺少什么?
【问题讨论】:
标签: c function pointers parameters dereference