迷惑C开头

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;
}

在文本中我需要将 c1 切换为 c2 并反转, 但是当我启动程序后,c1c2什么也没有发生。 我哪里错了?

首先,don't use gets(), it's inherently dangerous, use fgets()代替。

最重要的是,当您使用 gets(c1)c1 作为单元素数组时,您已经超出了调用 undefined behavior.

的已分配内存

就是说,您将 c1c2 作为单元素数组,这并没有错,但也不是必需的。将它们定义为简单的 char 变量

char c1;
char c2;

并像

一样使用它们
 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.

之后,a[i] == c2 的检查应该作为 else 构造,否则,您将覆盖之前的操作。像

for(i=0;i<n;i++)
{
    if(a[i]==c1)
   {
      a[i]=c2;
   }
  else if(a[i]==c2)
   {
    a[i]=c1;
   }
}
  • gets() 不应使用,因为它具有不可避免的缓冲区溢出风险,已在 C99 中弃用并从 C11 中删除。
  • c1c2 缓冲区大小不足。
  • 您应该检查读取是否成功。
  • 在比较检索读取的字符之前,您应该取消引用 c1c2
  • 你应该使用else if,否则修改后的字符会被再次修改

试试这个:

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

/* this is a simple implementation and the buffer for \n is wasted */
char* safer_gets(char* buf, size_t size){
  char* lf;
  if (fgets(buf, size, stdin) == NULL) return NULL;
  if ((lf = strchr(buf, '\n')) != NULL) *lf = '[=10=]';
  return buf;
}

int main()
{
  char a[250];
  char c1[4],c2[4]; /* need at least 3 elements due to the inefficient implementation of safer_gets */
  int n,i;


  printf("Give text: ");
  if(safer_gets(a, sizeof(a)) == NULL)
  {
    fputs("read a error\n", stderr);
    return 1;
  }

  printf("Give c1: ");
  if(safer_gets(c1, sizeof(c1)) == NULL)
  {
    fputs("read c1 error\n", stderr);
    return 1;
  }
  printf("Give c2: ");
  if(safer_gets(c2, sizeof(c2)) == NULL)
  {
    fputs("read c2 error\n", stderr);
    return 1;
  }

  n=strlen(a);

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