使用字符指针,while 循环中的 NULL

working with character pointers , NULL in while loop

我有问题请帮帮我

当我在 while 循环中写入 *str != '[=11=]' 时,字符串将正确输出,

但是当我在 while 循环中写 str != NULL 时,我的字符串将出现在输出中但带有奇怪的字符!我不知道为什么以及哪里出了问题!

#include <stdio.h>

void print(char* str)
{
  while (str != NULL) // *str != '[=10=]'
  {
    printf("%c",*str);
    str++;
  }
}

int main()
{ 
  char a[12]="hello world";
  print(a);

  return 0;
}

输出:hello worldÉ‼r╟‼@ py@ y┘JG¢╫☺√¶@4pdÜ∙⌂Q&8¢∙⌂0√ Φ♦0√ ╨♦↓

整个解释在于str是一个指针,它包含一个内存地址。您可以通过使用 *str.

取消引用来访问该内存位置中的内容

因此,当您使用 *str != '[=12=]' 时,您是在比较 str 指向的内存位置处的字符,这是正确的做法。而字符串的最后一个字符永远是这个特殊字符[=14=]。因此,该代码是正确的。

然而,当您执行 str != NULL 时,您要求检查内存地址本身,而不是其内容,并且地址在字符串末尾没有理由为 NULL。这就像走在一条街上,查看房屋的编号(内存地址),在某些房屋处字符串结束但沿街有更多的房屋,就像内存地址超出分配给字符串的内存地址一样,你是试图打印那些内存位置的内容,你不应该这样做,因为谁知道那里有什么。

*str 获取 str 指向的值。 str是指针本身的值。

例子where NULL points at and where the pointer str point at when using str points at the end of the string "ABC"

             NULL                           NULL pointer points to no valid value
                |
                |                      str  The str pointer points to '[=10=]', its value isn't NULL and most likely not 0
                V                       V 
                          +---+---+---+---+
Values       No value ... | A | B | C |[=10=] |
in Memory                 +---+---+---+---+
                ^           ^           ^
Example         |           |           |
Address         0   ...   0x1432 ... 0x1435