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') {更多推荐
发布评论