Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>sizeof(guess)</code> is returning the size of a <code>char *</code> <strong>not</strong> the length of the string <code>guess</code>. Your problem is that you're using <code>sizeof</code> to manage string lengths. C has a function for string length: <a href="http://en.cppreference.com/w/c/string/byte/strlen" rel="nofollow"><code>strlen</code></a>.</p> <p><code>sizeof</code> is used to determine the size of data types and arrays. <code>sizeof</code> only works for strings in one very specific case - I won't go into that here - but even then, always use <code>strlen</code> to work with string lengths. </p> <p>You'll want to decide how many characters you'll allow for your words. This is a property of your game, i.e. words in the game are never more that 11 characters long.</p> <p>So:</p> <pre><code>// define this somewhere, a header, or near top of your file #define MAX_WORD_LENGTH 11 // ... size_t wordlen = strlen(word); size_t guessLen; // MAX_WORD_LENGTH + 1, 1 more for the null-terminator: char *guess = malloc(sizeof(char) * (MAX_WORD_LENGTH + 1)); printf("Enter your guess: "); fgets(guess, MAX_WORD_LENGTH, stdin); guessLen = strlen(guess); </code></pre> <p>Also review the docs for <code>fgets</code> and note that the newline character <strong>is</strong> retained in the input, so you'll need to account for that if you want to compare the two words. One quick fix for this is to only compare up to the length of <code>word</code>, and <strong>not</strong> the length of <code>guess</code>, so: <code>if( strncmp(guess, word, wordLen) == 0)</code>. The problem with this quick fix is that it will pass invalid inputs, i.e. if <code>word</code> is <code>eject</code>, and <code>guess</code> is <code>ejection</code>, the comparison will pass.</p> <p>Finally, there's no reason to allocate memory for a new <code>guess</code> in each iteration of the loop, just use the string that you've already allocated. You could change your function setup to:</p> <pre><code>char guess(char *word, char *jumbledWord) { int exit; size_t wordLen = strlen(word); size_t guessLen; char *guess = malloc(sizeof(char) * (MAX_WORD_LENGTH + 1)); do { printf("Enter your guess: "); // ... </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload