簡體   English   中英

在C函數內部具有函數的參數和指針

[英]Parameters and pointers with function inside function in C

我在嘗試將指針用作另一個函數中某個函數的參數時遇到麻煩。 我的目標是在每個函數中保留變量“ 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 ++”命令后,它仍會繼續發送counter的“ -1”值。 為什么會發生這種情況,我該如何解決?

我認為問題可能出在commandInsert(id,tableHash,counter,flag)調用上,因為我沒有使用參考符號(&),但是由於它是參數,'counter'已經在identifyCommand()中時已經是一個指針,那么我在這里想念什么?

由於要更改counter指向的 ,因此應更改該值。 但是您正在增加指針。

counter++;

應該

(*counter)++;

如@szczurcio所述,您從中傳遞的command數組最多只能容納5個字符(NUL終止符為1個字符)。 因此, command數組的大小至少應為7才能讀取"INSERT" 為了防止緩沖區溢出,可以在scanf()使用寬度,例如:

char command[7];
scanf("%6s", command); 

或者,您可以使用fgets()

char command[7];
fgets(command, sizeof command, stdin);

char *p = strchr(command, '\n');
if (p) *p = 0;

但是,由於將command傳遞給函數,因此不能在函數內部使用sizeof command因為那樣會返回sizoof(char*) (將數組傳遞給函數時,它會變成指向其第一個元素的指針)。 因此,您必須通過另一個參數傳遞尺寸信息:

從呼叫者:

   while(1) {
     identifyCommand(command, sizeof command, id, &tableHash, flags, &counter);
   }

並在函數中:

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;

   ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM