c - 如何确定字符串长度?

标签 c string string-length

我一直很好奇如何决定字符串长度?
当我问我的老师这个问题时,他回答说“你必须假设一个值并分配给 srting”。
这最终将我引向了最初的问题:如何假设字符串的特定长度。我曾经考虑过内存分配,即我们通常都是这样写

char str[50] = "Hello world";

Here compiler allocates 50 bytes of memory for string str but only 10 bytes will be used and remaining 40 byte is wasted.

那么有没有办法在用户输入字符串后分配内存呢?

最佳答案

We used to give input about 20 to 30 input max so remaining are wasted

没错。您可以分配的金额没有限制,但如果您知道您不需要超过一定的金额,那么您可以只分配那么多。通常,对于在现代 PC 上运行的 Hello World,内存不会紧张,但如果您在数据库中存储数百万 strip 有名称等的记录,最好考虑一下内存消耗。

I even asked teachers is there any way that I can decler array size dynamically so that he replied answer "No" please help

您可以动态分配内存。假设您有这样的代码:

int n = 30;
char *string = malloc(n);
free(string); // any memory allocated with malloc should be freed when it is not used anymore

现在 string 的大小为 30,因为这是 n 设置的值,但它可以是其他任何值,在运行时确定。它可能是用户输入的内容。

在 C++ 中,有一个名为 std::string 的构造,它会自动为您执行动态内存分配。你可以做类似的事情

std::string s = "Hello";
s += " World";

而且您甚至不必担心内存分配。如果它内部不适合,它将使用摊销常量运行时间自行重新分配内存。

关于c - 如何确定字符串长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54302900/

相关文章:

无法保存 strlen 返回值

c - 桌面操作系统上的 C 编译器使用多少内存页来检测堆栈溢出?

c - 如何在 C 的 fortran 例程 "called"中分配一个数组

c++ - C 中的 undefined reference 错误

c - 如何通过名称获取 Windows 版本(对于 future 的 Windows 版本)?

C 返回字符串不正确

c - 为什么在 C 语言中字符串长度要加一其容量?

c# - 查找字符串中的所有大写字母 - 正则表达式 C#

input - 读取未知长度的字符串

java - 将新行读取为两个字符