繁体   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