Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

c++ - C ++在初始化char []和char之后,char显示在char []中(C++ after initialize char[] and char , char shows in the char[])

I'm learning Cpp recently, and today when I use Clion to learn do some testing strange thing happened.

(我最近在学习Cpp,今天,当我使用Clion学习做一些测试时,奇怪的事情发生了。)

Here is my code

(这是我的代码)


int main() {
    char c = 'b';
    char carr[1]{'a'};
    char *p1 =&(carr[0]);
    char *p2 =&c;
    return 0;
}

Complier:

(编译器:)

4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.33.8)

(4.2.1兼容的Apple LLVM 11.0.0(clang-1100.0.33.8))

lldb :

(lldb:)

数据库

And here is the details of memory:

(这是内存的详细信息:) 在此处输入图片说明

Please help me to figure out the reasons!

(请帮我找出原因!)

  ask by tzyrq translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The variable carr is of type char[1] which decays to char* .

(变量carr的类型为char[1] ,它会衰减为char* 。)

When trying to print a char* your debugger keeps printing chars until it reaches a null terminator \0 .

(尝试打印char*调试器将继续打印char,直到到达空终止符\0为止。)

It's not that carr contains "ab" , but rather that any function looking at carr would assume that it does.

(不是carr包含"ab" ,而是任何查看carr函数都假定它包含。)

This is because the bounds of the array are (almost always) discarded when it is passed to another function.

(这是因为当数组的边界传递给另一个函数时(几乎总是)将其丢弃。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...