Mat*_*ora 1 c parameters pointers function dereference
我在尝试将指针用作另一个函数内的函数的参数时遇到了一些麻烦.我的目标是在每个函数中保留变量'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;
}
Run Code Online (Sandbox Code Playgroud)
在我的.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;
}
Run Code Online (Sandbox Code Playgroud)
我的主要问题是:当我运行代码时,即使在commandInsert()函数中运行'counter ++'命令后,它也会继续发送计数器的'-1'值.为什么会发生这种情况,我该如何解决?
我想,也许问题出在commandInsert(ID,tableHash,计数器,旗)的调用,因为我没有使用符号(&),但"反"已经是一个指针,当内部identifyCommand(),因为它的参数那么我在这里错过了什么?
由于您要更改指向的值counter,因此应更改该值.但是你正在递增指针.
counter++;
Run Code Online (Sandbox Code Playgroud)
应该
(*counter)++;
Run Code Online (Sandbox Code Playgroud)
正如@szczurcio所指出的,command你传递的数组最多只能容纳5个字符(NUL终结符为1).因此,command数组的大小至少需要7才能读取"INSERT".要防止缓冲区溢出,可以使用宽度,scanf()例如:
char command[7];
scanf("%6s", command);
Run Code Online (Sandbox Code Playgroud)
或者你可以使用fgets().
char command[7];
fgets(command, sizeof command, stdin);
char *p = strchr(command, '\n');
if (p) *p = 0;
Run Code Online (Sandbox Code Playgroud)
但是,由于您传递command给函数,因此不能sizeof command在函数内部使用,因为它将返回sizoof(char*)(数组在传递给函数时衰减为指向其第一个元素的指针).所以你必须通过另一个参数传递大小信息:
来自来电者:
while(1) {
identifyCommand(command, sizeof command, id, &tableHash, flags, &counter);
}
Run Code Online (Sandbox Code Playgroud)
并在功能:
void identifyCommand(char* command, size_t size, int id, Hash* tableHash,
int* flag, int* counter){
fgets(command, size, stdin);
/* To remove the trailing newline, if any */
char *p = strchr(command, '\n');
if (p) *p = 0;
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
614 次 |
| 最近记录: |