【问题标题】:Segmentation fault when converting string to upper case将字符串转换为大写时出现分段错误
【发布时间】:2021-07-06 11:44:07
【问题描述】:

分段错误:有人可以帮助我理解我的错误吗?

目标:创建一个只有大写字母的新字符串。

另外,我试图通过参考 ASCII 表来识别我不想要的字母,希望这是正确的方法。

CS50 IDE,学习哈佛的 CS50 课程

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

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

int main(void)
{

    string word1 = get_string("Player 1: ");
    string word1CapsOnly="";
    char chr;
    
    for(int i=0; i<strlen(word1);i++)
    {
        if(word1[i]<123&&word1[i]>96)
        {
            // use to upper function
            // is lower would work here nicely
            chr = toupper(word1[i]);
            strncat(word1CapsOnly, &chr, 1);
            
        }
        else if(word1[i]<65 || word1[i]>122)
        {
            //ignore
        }
        else
        {
            //just add, upper alredy
            strncat(word1CapsOnly, &word1[i], 1);
        }
        
    }
    printf("%s", word1CapsOnly);
//     int score1 = compute_score(word1);
    // TODO: Print the winner
}

/* int compute_score(string word)
{
    // TODO: Compute and return score for string
    
} */

【问题讨论】:

  • AFAIK C 中没有 string ... 是 typedefchar * 吗?
  • 请显示minimal reproducible example。如果这是您的第一篇文章,您应该阅读我们的 tour 并阅读 How to Ask。也许看看reference for strncat,我认为你不明白它的作用。
  • @kiner_shah,照你说的做,谢谢
  • @selvin 欢迎来到 CS50,为了避免混淆,他们假装 C 确实string 类型。 (不用说,这种虚构实际上并没有避免混淆。)
  • 请不要编辑此问题来提出新问题。如果您有新问题,请ask a new question

标签: c cs50


【解决方案1】:

dowhile 循环在某些情况下会递增int n,直到在环绕后达到某个目标值,除了花费几分钟之外无济于事;它甚至没有计算出正确的wordScore。你最好去掉整个 for 循环,因为你显然只满足 ASCII,用简单的语句替换它:

      if (word[i]>='A' && word[i]<='Z') wordScore += POINTS[word[i]-'A'];

【讨论】:

    【解决方案2】:

    您的代码没有为word1CapsOnly 分配任何空间 - 它只是将其初始化为指向一个字符数组,该数组由一个包含 NUL(零)字符的字节组成。最简单的做法是先分配足够的空间:

    string word1CapsOnly = malloc(strlen(word1)+1);
    word1CapsOnly[0] = '\0';
    

    在 cs50.h 中,string 只是 char * 的同义词类型 - 它不会为你做任何内存管理。与 C 中的大多数字符串相关的东西一样,这一切都取决于你。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-21
      • 2013-08-31
      • 1970-01-01
      • 2018-07-29
      • 2017-08-01
      • 2011-09-15
      • 1970-01-01
      相关资源
      最近更新 更多