简体   繁体   中英

My small c program crashes

here is the program which is supposed to find the most common element in a string. But it crashes when I enter a string.

#include <stdio.h>
#include <conio.h>
#include <string.h>
int main(){
    char a[100];
    scanf("%s", a);
    int max=0,n,k;
    int urt = strlen(a);
    for(int i=0; i<urt-1; i++){
        n=0;
        for(int l=i+1; l<urt; l++){
            if(a[i]==a[l]) n++;
        }
        if(max<n){
            max=n; 
            k=i;
        }
    }
    printf("%s\n", a[k]);
    printf("%d", max);
    getch();
    return 0;
}

error: format '%s' expects argument of type 'char *', but argument 2 has type 'int'

Which means you need to change:

printf("%s\n", a[k]);

to:

printf("%c\n", a[k]);

because a[k] is not a string, but a character. Also to get a more accurate output, add 1 to n to consider the character you are scanning (from the outer loop):

n=1; // instead of n=0;

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