Logic errors and segmentation fault in C

This might not be c++, but I need help with this c program that I've been working on! There are logic errors producing incorrect results and possibly a segmentation fault in the following code.




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;
}
Here's a first hint for you. This is what my compiler warns me about when i compile your code:


(line 35): warning C4700: uninitialized local variable 'ch' used
(line 21): warning C4700: uninitialized local variable 'str' used
Topic archived. No new replies allowed.