need help with this C code

It compiles but it won't search the character that you want.


Enter a sentence to seach: hello world
Enter a character to search for: e
is found 0 times.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
  #include <stdio.h>
#include <string.h>

//Count the number of times the letter appears in the string
int count_letter(char str[], char ch) {
   int i, num = 0;
   
   for(i=0; i < strlen(str); i++)
      if(str[i] == ch)
	 num++;

   return num;
}

//Get the sentence and character to search for from the user
char * get_info(char ch) {
   char *str;
   int i=0; 

   printf("Enter a sentence to seach: ");
   while((str[i++]=getchar())!='\n');
   str[i]='\0'; 
   printf("Enter a character to search for: ");
   ch=getchar();

   return str;
}

//Get a sentence and character from the user and count the number
//of times the character is found in the sentence.
int main() {
   char *sentence, ch;
   int num_letters;

   sentence = get_info(ch);
   num_letters = count_letter(sentence, ch);

   printf("%c is found %d times.\n", ch, num_letters);
   
   return 0;
}
Line 17: str is an uninitialized pointer. Line 21 is storing characters into random memory if it doesn't crash.

Line 24: ch is passed by value. You're modifying a local copy of ch. The caller's instance of ch is not being updated. ch goes out of scope when get_info exits.




For line 17, could I add in NULL?

No. That would simply set the pointer to address 0, which is an illegal address reference on most machines.
Last edited on
Topic archived. No new replies allowed.