簡體   English   中英

為什么 const char 指針在 C 中分配給另一個?

[英]Why const char pointer assigned to another in C?

compute_scrabble_value函數中const char word[]被分配給const char *p

#include <stdio.h>
#include <ctype.h>

#define MAX_LEN 30

int compute_scrabble_value(const char *word);

const int scrabble_values[26] = {1, 3, 3, 2,  1, 4, 2, 4, 1, 8, 5, 1, 3,
                                 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10 };

int main(void)
{
    const char word[MAX_LEN + 1];
    printf("Enter a word: ");
    scanf("%s", word);
    printf("Scrabble value: %d", compute_scrabble_value(word));
    
    return 0;
}

int compute_scrabble_value(const char *word)
{
   const char *p = word;
   int total = 0;

   while (*p) {
       total += scrabble_values[toupper(*p++) - 'A'];
   }
      
   return total;
}

但即使你沒有像下面那樣分配,輸出看起來也是一樣的。

int compute_scrabble_value(const char *word)
{
   int total = 0;

   while (*word) {
       total += scrabble_values[toupper(*word++) - 'A'];
   }

   return total;
}

為什么將const char word[]分配給另一個指針變量?

沒有程序化的理由這樣做; 您的代碼直接使用word是等效的。

但是直接使用word會讓閱讀代碼的人感到困惑; 在第一個指針遞增之后, word不再指向實際的單詞,因此如果您以后需要將整個單詞作為一個整體來引用,則不能,但維護者可能認為您可以,因為您仍然有可用的word 將副本復制到p避免了變量名稱與其所代表的內容之間的語義分歧。 無論如何,優化編譯器可能會產生相同的機器代碼( word不再使用,因此wordp可以實現為同一個變量),即使它沒有,只要你沒有用完寄存器如果它實際上使用兩個不同的指針,這並不重要。

暫無
暫無

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

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