【问题标题】:Segmentation error in the program of searching for a string搜索字符串的程序中的分段错误
【发布时间】:2020-02-10 14:37:56
【问题描述】:

Q. 输入并存储 n 个字符串,然后搜索特定字符串

我可以输入“字符串数”,然后我也可以输入字符串。但是字符串不会被打印出来。比较和搜索都没有发生,它显示了一个分割错误。当我使用 gets() 输入字符串时会发生这种情况。 但是当我使用 scanf() 输入字符串时,程序会在我输入“字符串数”后立即终止。为什么会这样?

代码如下:

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

int main()
{
  char str[200],names[100];
  int n,i;
  int flag=0;

  printf("Give number of strings:\n");
  scanf("%d",&n);

  printf("Enter the strings:\n");
  for(i=0;i<n;i++)
  {
    gets(names);  
  }

  printf("Entered Values are:\n");
  for(i=0;i<n;i++)
  {
    printf("%s\t",names[i]);
  }

  printf("Enter the string you want to search for:\n");
  scanf("%s",str);
  for(i=0;i<n;i++)
  {
    if(strcmp(names[i],str) == 0)
       {
      flag=1;
      break;
       }
  }
  if(flag==1)
    printf("Yes this string %s exists!\n",str);
  else
    printf("No it does not exists");


  return 0;
}

【问题讨论】:

  • 这段代码应该给你各种类型不匹配的警告,尤其是关于在预期char*的地方使用char。先修好那些。提示:names[100]一个 字符串,而不是字符串数组。
  • Blaze 建议您打开编译器的警告(并听取它已经报告的错误)。
  • 他们所说的,而且永远不要使用gets。也不要使用conio.h
  • for循环内的gets(names);如何将读取的字符串放入names数组的条目中(假设它是一个字符串数组)?
  • 请参阅scanf() leaves the newline char in the buffer。另请注意,gets 已过时,您不应混合使用不同类型的输入函数。

标签: c arrays string search


【解决方案1】:
  1. gets 函数很危险,避免它。
  2. 您需要了解字符串是如何存储在内存中的。
char c[] = "Hello";` //is same as 
char c[5];
c[0] = 'H';
c[1] = 'e';
c[2] = 'l';
c[3] = 'l';
c[4] = '0';
c[5] = '/0';

在您的 sn-p 中,不是分配不同的数组来存储输入字符串,而是一次又一次地覆盖相同的数组。

为了存储n 字符串,您需要分配n 字符数组。 VLA 可用于分配 2D 数组,如 char names[n][100]nX100 大小。 names[0...n]代表二维矩阵中的一行,每行可以存储一个长度为100字节的字符串。

更新你的代码如下 sn-p,

char names[n][100];
printf("Enter the strings:\n");
for(i=0;i<n;i++)
{
   scanf("%99s",names[i]); //Avoid buffer overflow and mention max capacity
}

你可以找到完整的代码here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    相关资源
    最近更新 更多