如果字符串数组在C中以null终止,为什么其他数据类型的数组不以null终止? [英] If string arrays are null terminated in C, why are arrays of other data types not null terminated?

查看:111
本文介绍了如果字符串数组在C中以null终止,为什么其他数据类型的数组不以null终止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C中的字符串或字符数组必须以null结尾,以知道它们的结尾.为什么同一规则不适用于其他类型的数组? 例如.计算机如何知道整数数组的结尾位置?整数/浮点数/双精度数组在内存中的表示方式有何区别?

Strings, or arrays of characters in C must be null terminated to know where they end. Why does the same rule not apply to arrays of other types? eg. How does the computer know where an array of integers ends? Is there a difference in how arrays of integers/floats/doubles are represented in memory?

推荐答案

字符数组不必以nul结尾.

Arrays of characters do not have to be nul-terminated.

char foo[3]="foo"; //not nul-terminated
char bar[]={'b','a','r'}; //not nul-terminated

只是字符串文字是以nul终止的数组,而C则通过使用字符串文字作为初始值设定项,可以非常容易地创建以nul终止的数组:

It's just that string literals are nul-terminated arrays, and that C makes it really easy to make nul-terminated arrays by using string literals as initializers:

 char baz[]="baz"; //nul-terminated because "baz" is

设计者之所以选择C,是因为使用终止符似乎比保留字符数组后的字符计数更方便.

Why C does so is a choice the designer(s) made because using a terminator seemed more convenient to them than maintaining character counts next the character array.

但是C语言中没有任何东西会强加给您这种偏好.

But nothing in C forces this preference on you.

这篇关于如果字符串数组在C中以null终止,为什么其他数据类型的数组不以null终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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