0


I'm working on the readability task in pset2.
I've made a new function which is going to count each letter in a string.

What I want to do, is to get a user's input string, save it in a variable text and pass it to the function count_letters().
Inside the function, I filter out everything that is not chars of a-z and A-Z.
If I just spit out each char directly, inside the loop, it prints correct, and consolidates every word without spaces and special characters.

Inside the function, I'm also copying each char to a new array (the same letters I printed out the line above)
When I try to print out the new array, it only prints out the first word(where there is a space, or a special character).

Now, I don't understand what's happening here. Why isn't everything in the if-statement being properly copied into my new array? Why are spaces and special characters ignored inside the loop, but not ignored when they're copied from WITHIN the loop?

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


int count_letters(char *text);

int main(void)
{
  string text = get_string("Text: ");
  count_letters(text);
}

int count_letters(char *text)
{
  int l = strlen(text);
  char *letter_box = (char*)malloc(strlen(text+1));

  for(int i = 0; i < l; i++){

    if((text[i] >= 'a' && text[i] <= 'z') || (text[i] >= 'A' && text[i] <= 'z'))
    {
      letter_box[i] = text[i];
      printf("%c", text[i]); // PRINTS CORRECTLY
    }
  }
  printf("\n");
  printf("%s", letter_box); // ONLY PRINTS FIRST WORD

  return 0;
}
1
  • I realize I could just initialize a new int variable and increment it inside the loop. Still find the copy-behavior weird though. Commented May 7, 2020 at 6:53

1 Answer 1

1

It just so happens that the memory allocated to letter_box here

char *letter_box = (char*)malloc(strlen(text+1)); 

is all nulls (ie \0). Since the if loop will not change any non-alpha character (more or less, there is a typo in the if statement), the first \0 encountered is "end-of-string".

This letter_box[i] = text[i]; is fundamentally wrong, since there is not a one-to-one correspondence between the chars in letter_box and the chars in text.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .