0

I am new to c and I am getting the segmentation dump error after first printf statement. Please help me out with this error.

void main()
{
  char string[10]={};
  char key,used[10];
  int len=0;
  printf("Enter the string :");
  scanf("%s",&string);
  len = strlen(string);
  for (int i =0; i<len;++i)
  {
    int count=0;
    key =string[i];
    printf("%s",key);
    for (int j =0;j<len;++j)
    {
      if (string[j]==key)
      {
        count+=1;
      }
    }
    printf("%s %d",key,count);
  } 
}
Jerrymon
  • 109
  • 8
  • 1
    `printf("%s",key);` should be `printf("%c",key);`. `%s` expects null terminated `char *` but you are passing `char`. Develop good habit of considering compiler warnings. – kiran Biradar Oct 26 '18 at 07:15
  • Here char key is not array. Use key[size]. – danglingpointer Oct 26 '18 at 07:16
  • 1
    Besides taking heed to your compiler warnings (if yours didn't, it's settings aren't high enough and need to be raised), just take my word for it; being new to C, you simply cannot learn how to use a debugger soon enough. The sooner the better. You'll easily spend half your time using one over the course of a software engineering career. – WhozCraig Oct 26 '18 at 07:18
  • 1
    `printf("%s %d",key,count)` is also wrong. `key` is `char`, not `char[]`. – WhozCraig Oct 26 '18 at 07:18
  • 2
    `scanf("%s",&string);` should be `scanf("%s",string);` here's why :https://stackoverflow.com/questions/5406935/reading-a-string-with-scanf – Tom's Oct 26 '18 at 07:19
  • That is correct. – WhozCraig Oct 26 '18 at 07:43

1 Answers1

2

As mentioned in the comment

scanf("%s",&string); should be scanf("%s",string);

Use correct format specifier

printf("%s",key); should be printf("%c",key);//<-----should be %c
printf("%s %d",key,count); should be printf("%c %d",key,count);//<-----should be %c

suvojit_007
  • 1,690
  • 2
  • 17
  • 23