简单 C 代码中的分段错误(核心转储) [英] Segmentation fault (core dumped) in a simple C code
问题描述
我是 C 的新手.我指的是 Brian W Kernighian 和 Dennis Ritchie 所著的《The C Programming Language》一书.书中给出了指针递增和赋值的代码如下.
I am new in C. I am referring to the book "The C Programming Language" by Brian W Kernighian and Dennis Ritchie. There is a code for pointer increment and assignment given in the book as follows.
#include<stdio.h>
int main()
{
char *s = "Goal";
char *t = "Home";
while(*s++ = *t++) printf(*s);
return 0;
}
使用命令保存和编译代码
The code is saved and compiled using the command
gcc ptr.c -o ptr -std=c99
现在通过运行命令运行代码
Now on running the code by running command
./ptr
我收到以下错误
分段错误(核心转储)
错误似乎在 while
循环条件内.但代码与书中给出的完全相同.我错过了什么?
The error seems to be inside the while
loop condition.
But the code is exactly as given in the book.
What am I missing?
推荐答案
s
和 t
都是字符串文字,不能修改字符串文字.但是这段代码
s
and t
are both string literals, and you can't modify a string literal. But this piece of code
*s++ = *t++
会修改s
,导致分段错误.
will modify s
, which causes segmentation fault.
要修复它,请使用 char
数组.我还修改了 printf
部分以使其合法.
To fix it, use a char
array. I also modified the printf
part to make it legal.
#include<stdio.h>
int main()
{
char arr[] = "Goal";
char *s = arr;
char *t = "Home";
while(*s++ = *t++)
;
printf("%s
", arr);
return 0;
}
不过,我认为这个程序最好使用单独的函数来复制字符串,程序看起来会更清晰.
However, I think this program is better done using an individual function to copy the string, the program will look clearer.
#include<stdio.h>
void my_strcpy(char *s, char *t);
int main()
{
char s[] = "Goal";
char *t = "Home";
my_strcpy(s, t);
printf("%s
", s);
return 0;
}
void my_strcpy(char *s, char *t)
{
while(*s++ = *t++)
;
}
这篇关于简单 C 代码中的分段错误(核心转储)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!