简体   繁体   English

const char * 指针问题?

[英]Const char *pointer questions?

I have some questions related to this simple snippet of code.我有一些与这个简单的代码片段相关的问题。

#include <string.h>
#include <stdio.h>

int main()
{
   const char *str1;
   str1 = "hello";
   printf("%s \n", str1);
   return 0;
}

I want to ask you:我要问你:

  1. Is it safe to make an assignement to a const char pointer like that?像这样对 const char 指针进行赋值是否安全? Considering that str1 will never change.考虑到 str1 永远不会改变。
  2. Is it possibile that at the time of assignment str1 results NULL?是否有可能在赋值时 str1 结果为 NULL?

Thank you all!谢谢你们!

Is it safe to make an assignement to a const char pointer like that?像这样对 const char 指针进行赋值是否安全? Considering that str1 will never change.考虑到 str1 永远不会改变。

Yes.是的。 In fact, it's the right thing to do.事实上,这是正确的做法。

The pointer itself is not const ;指针本身不是const the type const char* means that the thing it points to is const .类型const char*意味着它指向的东西是const

If your pointer were const char* const str1 (a const pointer!) then you wouldn't be able to assign to it later.如果您的指针是const char* const str1 (一个 const 指针!),那么您以后将无法分配给它。 But you'd also get an error for not initialising it in the first place.但是你也会因为一开始没有初始化它而得到一个错误。

Is it possibile that at the time of assignment str1 results NULL?是否有可能在赋值时 str1 结果为 NULL?

No. The literal "hello" is never null.不。文字"hello"永远不会为空。 No string literal is ever null.没有字符串文字永远为空。

  1. It is safe to do the assignment.完成任务是安全的。
  2. After the assignment, str1 will point someplace in the initialized data of the image.赋值后, str1将指向图像初始化数据中的某个位置。 Just where is implementation-dependent.只是实现依赖于哪里。

Do not ever attempt to modify the memory at the place pointed to by str1 , for example by aliasing it with a non- const pointer.永远不要尝试修改str1的内存,例如通过使用非const指针对其进行别名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM