如何确定字符串长度?
How to decide string length?
一直很好奇如何决定字符串长度?
当我问老师这个问题时,他回答说 "you have to assume a value and allocate to 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 运行,您不会被内存所束缚,但是如果您在数据库中存储数百万条带有名称等的记录,则最好考虑一下内存消耗。
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";
而且您甚至不必担心内存分配问题。如果它在内部不适合,它将使用摊销的常量运行时间自行重新分配内存。
一直很好奇如何决定字符串长度?
当我问老师这个问题时,他回答说 "you have to assume a value and allocate to 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 运行,您不会被内存所束缚,但是如果您在数据库中存储数百万条带有名称等的记录,则最好考虑一下内存消耗。
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";
而且您甚至不必担心内存分配问题。如果它在内部不适合,它将使用摊销的常量运行时间自行重新分配内存。