You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scrabble开发项目:将string转为字符数组时遇类型不兼容错误

解决CS50 Scrabble游戏中的字符串转字符数组错误及得分计算问题

错误原因分析

你遇到的编译错误核心是类型不匹配+数组越界:

  • CS50的string是char*的别名,你试图把一个指针(word)赋值给单个char类型的数组元素wordarray[wordlength],这必然导致类型转换错误。
  • 同时,char wordarray[wordlength]的有效索引范围是0到wordlength-1,wordarray[wordlength]已经超出数组边界,属于非法内存访问。

更关键的是:你根本不需要手动把string转成字符数组——CS50的string本身就是指向字符数组的指针,可以直接遍历每个字符。

修正后的完整得分计算函数

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

// Points assigned to each letter of the alphabet
int POINTS[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 compute_score(string word);

int main(void)
{
    // Get input words from both players
    string word1 = get_string("Player 1: ");
    string word2 = get_string("Player 2: ");

    // Score both words
    int score1 = compute_score(word1);
    int score2 = compute_score(word2);

    // Print the winner
    if (score1 > score2) {
        printf("Player 1 is the winner!\n");
    } else if (score1 < score2) {
        printf("Player 2 is the winner!\n");
    } else {
        printf("It is a tie!\n");
    }
}

int compute_score(string word)
{
    int playerscore = 0;
    int wordlength = strlen(word);
    
    // 直接遍历原字符串的每个字符
    for (int i = 0; i < wordlength; i++) {
        char letter = tolower(word[i]);
        
        // 仅处理字母字符,非字母不计分
        if (letter >= 'a' && letter <= 'z') {
            // 通过字符ASCII值差直接计算索引,无需遍历字母数组
            int index = letter - 'a';
            playerscore += POINTS[index];
        }
    }
    
    return playerscore;
}

关键修正点说明

  1. 移除冗余的字符数组转换:直接通过word[i]访问字符串的每个字符,完全不需要额外创建wordarray。
  2. 优化索引计算逻辑:用letter - 'a'直接得到字母在POINTS数组中的索引(比如'a'-'a'=0,对应POINTS[0]的1分),避免低效的双重循环遍历字母数组。
  3. 增加非字母过滤:确保空格、符号等非字母字符不会参与计分,避免潜在的数组越界问题。
  4. 修正循环条件:预先计算字符串长度并作为循环上限,避免每次循环调用strlen的性能损耗。

若坚持手动复制字符数组(无必要但供参考)

如果一定要手动将字符串复制到新数组,需注意预留字符串结束符'\0'的位置,并用strcpy完成复制:

int wordlength = strlen(word);
char wordarray[wordlength + 1]; // 多留一个位置存'\0'
strcpy(wordarray, word);

内容的提问来源于stack exchange,提问作者Michael Agunga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 14:15:54