正在修改字符串通过有效的指针指向? [英] Is modifying a string pointed to by a pointer valid?
本文介绍了正在修改字符串通过有效的指针指向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是连接两个字符串程序的一个简单的例子。
Here's a simple example of a program that concatenates two strings.
#include <stdio.h>
void strcat(char *s, char *t);
void strcat(char *s, char *t) {
while (*s++ != '\0');
s--;
while ((*s++ = *t++) != '\0');
}
int main() {
char *s = "hello";
strcat(s, " world");
while (*s != '\0') {
putchar(*s++);
}
return 0;
}
我不知道为什么它的工作原理。在main(),我有一个指向字符串hello。按照K&放大器; R书,修改这样的字符串是未定义的行为。那么,为什么是程序能够通过附加的世界进行修改?或者追加不被视为修改?
I'm wondering why it works. In main(), I have a pointer to the string "hello". According to the K&R book, modifying a string like that is undefined behavior. So why is the program able to modify it by appending " world"? Or is appending not considered as modifying?
推荐答案
未定义行为意味着一个编译器能发出code,做任何事情。工作是不确定的一个子集。
Undefined behavior means a compiler can emit code that does anything. Working is a subset of undefined.
这篇关于正在修改字符串通过有效的指针指向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文