【发布时间】:2017-04-26 10:59:09
【问题描述】:
我需要帮助理解的内容:
我正在尝试了解我遇到的分段错误:
分段错误(核心转储)
从查看 SO 和 Google 来看,这似乎与尝试访问代码在某些范围内无法访问的内存有关。但是我似乎无法弄清楚它发生在哪里。
我正在尝试做什么(期待):
我正在学习 C 编程语言并尝试解决练习 2.4:squeeze(s1, s2) - 在 s1 中删除 s2 中的所有字符实例。
我还没有接触到动态数组等,所以我只能“能够”(从最温和的意义上说)使用简单的原始数据类型。不过,我有使用高级语言的经验!
我做了什么:
我在 Windows 10 机器上运行 CygWin,编译器 (gcc) 没有问题。
这是我为解决上述问题而编写的代码:
/*
Exercise 2.4
squeeze (s1, s2): Remove all characters of s2 in s1.
INPUT : s1.length >= s2 > 0.
OUTPUT: The rest of s1 after deleting all occurances of letters in s2.
*/
#include <stdio.h>
void squeeze (char s1[], const char *s2); /* Returns (by-ref) the resulting string s1 after removing all occurences of s2. */
int toUpper(char c); /* returns the numerical representation of a hexadecimal digit. */
int main () {
char s1[] = "I am a test.\0";
const char *s2 = "AE\0";
printf("Before manipulation: %s\n", s1);
squeeze(s1, s2);
printf("After manipulation: %s", s1);
}
/*
Returns the (by-ref) resulting string s1 after removing all occurences
of letters in s2.
*/
void squeeze (char s1[], const char *s2) {
int index, s2_index, c = 0;
while (s1[index] != '\0') {
while(s2[s2_index] != '\0') {
if ((c = toUpper(s1[index])) == s2[s2_index]){
s1[index] = s1[index + 1];
}
s2_index++;
}
s2_index = 0;
index++;
}
}
/*
Returns the upper-case representation of char c.
*/
int toUpper (char c) {
if (c >= 'a' && c <= 'z')
return c - 32;
else
return c;
}
干杯!如果您有任何问题或我遗漏了什么,请随时发表评论! :)
感谢您的帮助!
【问题讨论】:
-
index和s2_index未初始化。 -
这真的很好奇。它解决了我的问题。但现在我很困惑。那个语法不是应该意味着
c = 0, s2_index = c and index = s2_index吗? -
不,不是。如果能这样工作就好了。
-
哈哈。我的错。一定是书上看错了。感谢您的澄清! :)
-
它几乎是重复的:stackoverflow.com/q/6838408/4996248(尽管 C++ 和 C 不是同一种语言,但它们在这里没有区别)。
标签: c arrays segmentation-fault