在在C字节获得字符串大小 [英] get string size in bytes in c

查看:166
本文介绍了在在C字节获得字符串大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所暗示的,你能告诉我如何得到一个字符串(空终止)的规模保持在一个字符数组c ?这是很好的使用的sizeof 如果我宣布它(串)的功能,而不的malloc init或如果我宣布它作为指针?如果我用的malloc 初始化呢?我想有这个问题的详尽答复。

As the title imply, can you tell me how to get the size of a string (null terminated) kept in a char array in c? It's good to use sizeof if I declared it (the string) in a function without malloc init or if I declared it as a pointer? What if I initialized it with malloc? I would like to have an exhaustive response to that question.

推荐答案

您可以使用 strlen的。大小由终止空字符决定的,因此传入的参数应该是有效的。

You can use strlen. Size is determined by the terminating null-character, so passed string should be valid.

如果你想要得到的内存缓冲区的大小,包含您的字符串,你必须指向它的指针:

If you want to get size of memory buffer, that contains your string, and you have pointer to it:


  • 如果它是动态阵列(使用malloc创建的),这是不可能得到
    它的大小,因为编译器不知道指针正指向。
    (<一href=\"http://stackoverflow.com/questions/492384/how-to-find-the-sizeofa-pointer-pointing-to-an-array\">check这)

  • 如果是静态数组,可以使用的sizeof 来获得它的大小。

  • If it is dynamic array(created with malloc), it is impossible to get it size, since compiler doesn't know what pointer is pointing at. (check this)
  • If it is static array, you can use sizeof to get its size.

如果你感到困惑的动态和静态数组之间的差异,请这个

If you are confused about difference between dynamic and static arrays, check this.

这篇关于在在C字节获得字符串大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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