Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't figure out this segmentation fault

I’m quite new to programming and I am in the middle of doing CS50, and in this scrabble program I’m having trouble because I can’t figure out which segmentation error I am making. It may be that my index is outside my array. If you could find the problem and also explain it to me I would be grateful.

#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 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);
if (score1 > score2)
{
    printf("Player 1 wins!\n");
}
else if (score1 == score2)
{
    printf("Tie!\n");
}
else
{
    printf("Player 2 wins!\n");
}
    // TODO: Print the winner
}

int compute_score(string word)
{
    int number;
    int sum1=0;
for (int i = 0; i<strlen(word); i++)
{
  if (isupper(word))
  {
      number = POINTS[word[i]-'A'];
 }
 else if (word[i] < 97 || word[i]>122 || word[i]<65 || word[i]>90)
   {
        number = 0;
   }
   else
   {
     number = POINTS[word[i] - 'a'];
   }
   sum1 = sum1 + number;
}
   return sum1;
    // Assign points to letters
    // read the letters in the word
    // covert the letters into scores and add
    // TODO: Compute and return score for string
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

At least this condition in the if statement

 if (isupper(word))

is incorrect. You have to write

if (isupper( ( unsigned char )word[i]))

The condition in this if statement

 else if (word[i] < 97 || word[i]>122 || word[i]<65 || word[i]>90)

does not make a sense. For starters do not use magic numbers like for example 97. The condition can look like

else if ( !( ( word[i] >= 'a' && word[i] <= 'z' ) || ( word[i] >= 'A' && word[i] <= 'Z' ) ) )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading