英文:
Error: Process finished with exit code 138 (interrupted by signal 10: SIGBUS)
问题
我正在学习C编程,我编写了一个函数,并想看看它是如何工作的。
以下是代码片段:
#include <stdio.h>
void squeeze(char s[], int c) {
int i, j;
for (i = j = 0; s[i] != '#include <stdio.h>
void squeeze(char s[], int c) {
int i, j;
for (i = j = 0; s[i] != '\0'; i++) {
if (s[i] != c)
s[j++] = s[i];
}
s[j] = '\0';
printf("Converted: %s", s);
}
int main() {
squeeze("abcdefghigk", 'c');
}
'; i++) {
if (s[i] != c)
s[j++] = s[i];
}
s[j] = '#include <stdio.h>
void squeeze(char s[], int c) {
int i, j;
for (i = j = 0; s[i] != '\0'; i++) {
if (s[i] != c)
s[j++] = s[i];
}
s[j] = '\0';
printf("Converted: %s", s);
}
int main() {
squeeze("abcdefghigk", 'c');
}
';
printf("Converted: %s", s);
}
int main() {
squeeze("abcdefghigk", 'c');
}
但是当我运行它时,收到了以下错误:
进程以退出码138(被信号10:SIGBUS中断)结束
我使用的是MacBook M1,OS 13.4,Clion C23标准。
期望的结果是:
abdefghigk
但终端中没有显示任何内容,我在传递参数时出错了吗?
我已经查看了这个问题,它看起来很相似,但我不太理解答案,有人能帮忙解释一下吗?
英文:
I'm learning C programming and I wrote a function and wanted to see how it work.
Here is the snippet:
#include <stdio.h>
void squeeze(char s[], int c) {
int i, j;
for (i = j = 0; s[i] != '#include <stdio.h>
void squeeze(char s[], int c) {
int i, j;
for (i = j = 0; s[i] != '\0'; i++) {
if (s[i] != c)
s[j++] = s[i];
}
s[j] = '\0';
printf("Converted: %s", s);
}
int main() {
squeeze("abcdefghigk", 'c');
}
'; i++) {
if (s[i] != c)
s[j++] = s[i];
}
s[j] = '#include <stdio.h>
void squeeze(char s[], int c) {
int i, j;
for (i = j = 0; s[i] != '\0'; i++) {
if (s[i] != c)
s[j++] = s[i];
}
s[j] = '\0';
printf("Converted: %s", s);
}
int main() {
squeeze("abcdefghigk", 'c');
}
';
printf("Converted: %s", s);
}
int main() {
squeeze("abcdefghigk", 'c');
}
But when I run it, I received this:
Process finished with exit code 138 (interrupted by signal 10: SIGBUS)
I'm using macbook M1, OS13.4, Clion C23 standard.
Result expected:
abdefghigk
But nothing showed up in the terminal, did I make mistakes when pass the arguments?
I have reviewed this issue, it looks similiar, but I'm not quite understand the answers, could someone please help explain?
答案1
得分: 0
修改字符串字面量是未定义行为。
来自C标准(6.4.5 字符串字面量)
7 不确定这些数组是否不同,只要它们的元素具有适当的值即可。如果程序尝试修改这样的数组,则行为是未定义的。
使用数组来表示字符串:
char input[] = "abcdefghigk";
squeeze(input, 'c');
英文:
It is undefined behavior to modify a string literal.
From the C Standard (6.4.5 String literals)
> 7 It is unspecified whether these arrays are distinct provided their
> elements have the appropriate values. If the program attempts to
> modify such an array, the behavior is undefined.
Use an array for the string:
char input[] = "abcdefghigk";
squeeze(input, 'c');
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论