c - 为什么段错误: 11 occurred for my C code?

标签 c segmentation-fault c-strings

我尝试编写一个函数,删除字符串 s1 中与字符串 s2 中任何字符匹配的每个字符。 这是挤压方法的测试代码。

#include <stdio.h>

void squeeze(char s1[], char s2[]);

int main()
{
    char s1[20] = "HelloWorld", s2[20] = "ol"; 
    squeeze(s1, s2); 
    printf("%s\n", s1); 
    return 0; 
}

void squeeze(char s1[], char s2[])
{
    int i, j, k; 
    k = 0; 
    for (i = 0; s1[i] != '\0'; ++i) {
        for (j = 0; s2[j] != '\0'; ++j) {
            if (s1[i] != s2[j])
                s1[k++] = s1[i];
        }
    }
    s1[k] = '\0';
}

当我运行此代码时,终端总是给出段错误:11。 谁能给我任何提示为什么会发生这种情况?

最佳答案

示例:

#include <stdio.h>

static int found(char *str, char c) { //  return 1 if c is found in str
  for (size_t i = 0; str[i] != '\0'; i++) {
    if (str[i] == c) {
      return 1;
    }
  }
  return 0;
}

static void squeeze(char *a, char *b) {
  size_t k = 0;
  for (size_t i = 0; a[i] != '\0'; i++) { // use size_t to iterate on a c-string
    if (found(b, a[i]) != 1) { 
      a[k++] = a[i]; // copy only if a[i] is not in b
    }
  }
  a[k] = '\0';
}

int main(void) {
  char a[] = "HelloWorld"; // you should let auto size
  char b[] = "ol";         // and separate declaration

  squeeze(a, b);

  printf("%s\n", a);
}

关于c - 为什么段错误: 11 occurred for my C code?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41484825/

相关文章:

c - extern C 中的字符串数组

c - 如何在 macOS 上使用 Mach 内核设置主机异常端口?

c++ - 使用克隆(): segmentation fault

c++ - 返回填充在函数内部的 const char* vector 是否是明确定义的行为

C 错误 :format '%s' expects argument of type 'char *' but argument 2 has type 'char (*)[100]'

c - 如何在不使用strcmp的情况下比较两个二维字符串

c - C中的MPI。在 I_send 和 Irecv 中使用循环

C:在第一次连接时发送/接收部分数据包,在第二次连接时接收其余数据包

c - 段错误和 printf 警告

c - C 语言 Trie 实现中的段错误