如何在c中的某个位置终止字符指针? [英] How to terminate a character pointer at a certain location in c?
问题描述
我正在尝试通过将null终止符设置为特定位置终止c中的字符指针.
I'm trying to terminate a character pointer in c, at a specific location by setting the null terminator to it.
例如,如果我有一个char指针
for examples if I have a char pointer
char *hi="hello";
我希望通过将o
设置为null来将其设置为"hell"
.
I want it to be "hell"
by setting the o
to null.
我已经尝试使用
strcpy(hi+4, "\0");
但是它不起作用.
推荐答案
"hello"
是字符串文字,因此无法修改,在您的代码中,hi
指向此类文字中的第一个元素.任何试图修改它指向的东西的尝试都是未定义的行为.
"hello"
is a string literal so it cannot modified, and in your code, hi
points to the first element in such a literal. Any attempt to modify the thing it points to is undefined behaviour.
但是,如果您创建自己的char
数组,则可以随意插入一个空终止符.例如,
However, if you create your own char
array, you can insert a null terminator at will. For example,
char hi[] = "hello"; // hi is array with {'h', 'e', 'l', 'l', 'o', '\0'}
hi[4] = '\0';
在这里,hi
是您拥有的char
的长度6数组,可以更改其内容.设置第5个元素后,它包含{'h', 'e', 'l', 'l', '\0', '\0'}
,并且打印出来将产生hell
.
Here, hi
is a length 6 array of char
which you own and whose contents you can modify. After setting the 5th element, it contains {'h', 'e', 'l', 'l', '\0', '\0'}
, and printing it would yield hell
.
这篇关于如何在c中的某个位置终止字符指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!