使用malloc分配时是否包含空字符 [英] Is null character included while allocating using malloc

查看:170
本文介绍了使用malloc分配时是否包含空字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用C相当一段时间了,我有这个琐碎的问题要查询.

I have been using C for quite sometime, and I have this trivial problem that I want to query about.

说我想创建一个字符数组,最多可存储1000个字符.现在,当我同时使用malloc时,我是否将数组的大小指定为1001个字符[1000个字符+ null]或仅1000个?

Say i want to create a character array that stores upto 1000 characters. Now, when I am using malloc for the same, then do I specify the size of array as 1001 character [ 1000 characters + null] or just 1000?

另外,说我遇到了这个问题,那么我怎么可能自己通过使用一些测试程序找到解决方案的答案.我知道字符串的大小是在不包含空字符的情况下计算的,但是当我为相同的内存分配内存时,我是否也考虑了空字符吗?

Also, say I came across this problem, then how could I have found the answer to this solution on my own, maybe by using some test programs. I understand the size of string is calculated without the null character, but when I am allocating the memory for the same, do I take into account the null character too?

推荐答案

如果您需要该块来存储以null终止的字符串,那么是的,您需要明确要求malloc()分配一个额外的字节来存储null终止符,否则malloc()不会为您完成此操作.如果您打算将字符串长度存储在其他位置,因此不需要空终止符,则可以在不分配额外字节的情况下摆脱困境.当然,是否需要字符串的终止符取决于您,只是不要忘记C库字符串处理函数仅适用于终止符为null的字符串.

If you need that block for storing null-terminated string then yes, you need to explictly ask malloc() to allocate an extra byte for storing the null-terminator, malloc() will not do it for you otherwise. If you intend to store the string length somewhere else and so you don't need the null terminator you can get away without allocating the extra byte. Of course it's up to you whether you need null-termination for strings, just don't forget that C library string handling functions only work with null-terminated strings.

这篇关于使用malloc分配时是否包含空字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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