我尝试编写一个函数,删除字符串 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/