Home > front end >  Can't figure out this segmentation fault
Can't figure out this segmentation fault

Time:05-28

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
}

CodePudding user response:

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' ) ) )
  • Related