C - K&R 练习 2.4 - 为什么我会收到总线错误?
为什么我会收到总线错误?有问题的行已标记在代码内。
练习2-4。 编写 scrape(s1,s2) 的替代版本,删除 s1 中与字符串 s2 中任何字符匹配的每个字符。
#include <stdio.h>
/*
* Detects if a char is inside a string
*/
char in_string(char c, char s[]) {
int i = 0;
while (s[i] != '\0') {
if (s[i++] == c)
return 1;
}
return 0;
}
/*
* Returns the string s without any chars that are in map
*/
void squeeze(char s[], char map[]) {
int i, j;
for (i = j = 0; s[i] != '\0'; i++) {
if (! in_string(s[i], map)) {
s[j++] = s[i]; // <--- Bus Error
}
}
s[j] = '\0';
printf("%s\n", s);
}
main() {
squeeze("XALOMR", "AO");
squeeze("EWRTOG", "RGV");
}
Why am I getting a bus error? The problematic line is marked inside the code.
Exercise 2-4.
Write an alternative version of squeeze(s1,s2) that deletes each character in s1 that matches any character in the string s2.
#include <stdio.h>
/*
* Detects if a char is inside a string
*/
char in_string(char c, char s[]) {
int i = 0;
while (s[i] != '\0') {
if (s[i++] == c)
return 1;
}
return 0;
}
/*
* Returns the string s without any chars that are in map
*/
void squeeze(char s[], char map[]) {
int i, j;
for (i = j = 0; s[i] != '\0'; i++) {
if (! in_string(s[i], map)) {
s[j++] = s[i]; // <--- Bus Error
}
}
s[j] = '\0';
printf("%s\n", s);
}
main() {
squeeze("XALOMR", "AO");
squeeze("EWRTOG", "RGV");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为
"XALOMR"
是一个字符串文字(只读),您无法修改它(就像您在此处所做的那样:s[j++] = s[i];
)解决方法是:
这将在堆栈上创建一个字符数组。
Because
"XALOMR"
is a string literal (which is read-only) and you cannot modify it (as you do here:s[j++] = s[i];
)A way around it is:
Which will create an array of chars on the stack.
当您尝试更改字符串文字时,您可能会遇到错误。
真正发生的是代码的行为是未定义的。运气好的话,就会犯错。如果运气不好,代码看起来会按预期工作,这使得错误很难被发现。
顺便说一句,您可以声明一个 char 数组,该数组从用于初始化它的字符串文字获取其大小:
When you try to change a string literal, you might get a fault.
What really happens is that the behavior of your code is undefined. If you're lucky, you'll get a fault. If you're unlucky, the code will appear to work as expected, which makes the error difficult to find.
Incidentally, you can declare a char array that gets its size from the string literal used to initialize it:
字符串文字是只读的。当你试图改变它时,你就会犯错。
Strings literals are read-only. When you try to change it, you get a fault.
如果你想修改它们,你需要创建这些变量。
You need to make these variables if you want to modify them.