C中结束char * [关闭](End of char* in C [closed])

编程入门 行业动态 更新时间:2024-10-25 22:24:23
C中结束char * [关闭](End of char* in C [closed])

我有这样的代码

int main() { char* word = "kotok"; char* word1 = word; while (word1 != '\0'){ printf("%s ", word1); word1++; } return 0; }

但是在打印“kotok,otok,tok,ok,k”之后它并没有结束。 此代码继续打印一些垃圾,然后停止。 怎么克服它?

我试着添加word1[strlen(word1)] = '\0'; 但它给出了分段错误。

I have such piece of code

int main() { char* word = "kotok"; char* word1 = word; while (word1 != '\0'){ printf("%s ", word1); word1++; } return 0; }

But it doesn't end after printing "kotok, otok, tok, ok, k". This code continues prints some garbage and then stops. How to overcome it?

I tried to add word1[strlen(word1)] = '\0'; but it gives a segmentation fault.

最满意答案

word1是一个指针。 '\0'是一个角色。 这就是为什么word1 != '\0'没有达到预期的效果。

您必须取消引用指针以获取它指向的字符:

while (*word1 != '\0') {

word1 is a pointer. '\0' is a character. This is why word1 != '\0' doesn't do what you expect.

You have to dereference the pointer to get the character it points to:

while (*word1 != '\0') {

更多推荐

本文发布于:2023-07-22 18:31:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1222352.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:结束   char   closed

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!