Search code examples
carrayscharfgets

Confusion C begining


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


int main()
{
 char a[250];
 char c1[1],c2[1];
int n,i;


printf("Give text: ");
gets(a);

printf("Give c1: ");
gets(c1);
  printf("Give c2: ");
 gets(c2);

n=strlen(a);

for(i=0;i<n;i++)
{
    if(a[i]==c1)
 {
      a[i]=c2;
   }
  if(a[i]==c2)
 {
    a[i]=c1;
   }
   }
     printf("%s",a);
return 0;
}

In a text I need to switch c1 with c2 and reverse, but when I start the program after I give a, c1, c2 nothing happened. Where am I wrong?


Solution

  • First of all, don't use gets(), it's inherently dangerous, use fgets() instead.

    On top of that, when you used gets(c1), c1 being an one-element array, you already overrun the allocated memory which invokes undefined behavior.

    That said, you have c1 and c2 as one-element arrays, which are not wrong but neither required. Define them as simple char variables

    char c1;
    char c2;
    

    and use them like

     scanf(" %c", &c1);  // mind the space and don't forget to to check the return 
     scanf(" %c", &c2);  // value of scanf() to ensure proper scanning.
    

    After that, the check for a[i] == c2 should come as else construct, otherwise, you'll be overwriting the previous operation. Something like

    for(i=0;i<n;i++)
    {
        if(a[i]==c1)
       {
          a[i]=c2;
       }
      else if(a[i]==c2)
       {
        a[i]=c1;
       }
    }