为什么分段错误:我的C代码发生了11?

时间:2017-01-05 12:12:31

标签: c segmentation-fault c-strings

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

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

当我运行此代码时,终端始终提供Segmentation fault: 11。 有人可以给我任何提示,为什么会这样?

2 个答案:

答案 0 :(得分:0)

示例:

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

答案 1 :(得分:0)

您的代码问题是s1[k++] = s1[i];

尝试使用新阵列

参见以下代码

#include<stdio.h>

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

int main()
{
    char s1[20] = "HelloWorld", s2[20] = "olH";

    squeeze(s1, s2);

    return 0;
}


char *squeeze(char s1[], char s2[])
{
    int i, j, k;

    k = 0;

    char arr[100]; // new array

    int flag = 0;
    for (i = 0; s1[i] != '\0'; i++) {
        flag = 0;

        for (j = 0; s2[j] != '\0'; ++j) {
            if (s1[i] == s2[j])
            {
                flag = 1;
                break;
            }
        }

        if (flag == 0)
        {
            arr[k++] = s1[i];
        }
    }

    arr[k] = '\0';

    printf("%s",arr);
}