C语言中的Sizeof(char []) [英] Sizeof(char[]) in C

查看:141
本文介绍了C语言中的Sizeof(char [])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

 char name[]="123";
 char name1[]="1234";

结果

The size of name (char[]):4
The size of name1 (char[]):5

为什么char[]的大小总是加一?

Why the size of char[] is always plus one?

推荐答案

正如Michael在注释中指出的那样,字符串以零结尾.因此,在内存中,第一个字符串将如下所示:

As Michael pointed out in the comments the strings are terminated by a zero. So in memory the first string will look like this

"123\0"

其中\0是单个字符,并且ASCII值为0.那么上面的字符串的大小为4.

where \0 is a single char and has the ASCII value 0. Then the above string has size 4.

如果您没有此终止符,那么怎么知道字符串(或char[])在哪里结束?好吧,实际上另一种方法是将长度存储在某个地方.一些语言可以做到这一点. C没有.

If you had not this terminating character, how would one know, where the string (or char[] for that matter) ends? Well, indeed one other way is to store the length somewhere. Some languages do that. C doesn't.

这篇关于C语言中的Sizeof(char [])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆