简体   繁体   中英

Program in c crashes

My code seems to crash everytime i run it, i want to make a program that finds a capital letter in a sentence (str[max]) and it prints out how many times it finds it

i get a warning from the build log (warning: 'c' may be used uninitialized in this function) (very entry level programmer here !!)

#include <stdio.h>
#include <string.h>
#include "genlib.h"
#include "simpio.h"
#include "ctype.h"


#define max 26

void checktimes(char str[],char temp);

int main()
{
char str[max], temp;
printf("Type a sentence with 25 characters max :");
gets(str);

int i;
for(i=0;i<=max;i++)
{
temp = str[i];
 if(isupper(temp))
    checktimes(str,temp);
}
 return 0;
}

void checktimes(char str[],char temp)
{
int j,i;
char c;
for(j=0; j<=max ; j++)
{
    str[i] = c;
    if(c == temp)
        i++;
}
printf("%c --> %d",temp,i);

}

You have multiple problems:

1) Never use gets() . Use fgets() instead.

2) You may not always have max number of characters. So, your condition: for(i=0;i<=max;i++) is probably wrong. Use strlen() to find out the actual number of chars in str .

3) You are reading c uninitialized here:

str[i] = c;

You probably meant:

c = str[j]; /* notice the i -> j change */

4) The argument to isupper() requires a cast to unsigned char .

5) Initialize i to 0 in checktimes() .


In fact, there's a logical error as well. You would be printing the count of duplicate chars as many times. If you use an temp array, it can be written as:

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

#define max 26

void checktimes(char str[]);

int main(void)
{
    char str[max];
    printf("Type a sentence with 25 characters max :");
    fgets(str, sizeof str, stdin);
    str[strcspn(str, "\n")] = 0; /* To remove the trailing newline if any. */
    checktimes(str);
    return 0;
}

void checktimes(char str[])
{
    int i = 0;
    int count[max] = {0};
    size_t len = strlen(str);
    for(i=0; i<len; i++)
    {
        if(isupper((unsigned char)str[i]))
            count[str[i] - 'A']++;
    }
    for(i = 0; i < max; i++)
    if (count[i])
        printf("%c --> %d\n",i+'A', count[i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM