gpt4 book ai didi

c++ - 确定动态内存分配中 char 指针的最大容量

转载 作者:行者123 更新时间:2023-11-30 03:43:08 25 4
gpt4 key购买 nike

首先,我想澄清的是,这是我过去的家庭作业,但我无法弄清楚,我仍在努力思考。这些是辅助构造函数的说明:

NIUString::NIUString(const char* other)

This constructor for the NIUString class should initialize a new NIUString object to the C string other. The required logic is:
Set the string size for the new object to the length of the C string other.
Set the string capacity for the new object to the string size.
If the string capacity is 0, set the string array pointer for the new object to nullptr. Otherwise, use the string array pointer for the new object to allocate an array of char. The number of elements in the new string array should be equal to the string capacity.
Copy the characters of the C string other (up to, but not including the null character) into the string array.

对于我的输出,我应该得到

testing second constructor
s2: some text
s2 size: 9
s2 capacity: 9
s2 is not empty

但我却……

testing second constructor
s2: some text
s2 size: 9
s2 capacity: 8
s2 is not empty

经过研究,我了解到这是因为您不能对指针使用 sizeof,因为它只会为您提供内存中指针的大小,而不是字符串的实际大小容量。

这是我编写的方法的代码

//secondary constructor
NIUString::NIUString( const char* other)
{
Capacity = sizeof(other);
Size = strlen(other);

if (Capacity == 0)
{
arrayPoint = nullptr;
}
else
arrayPoint = new char[Capacity];
strcpy(arrayPoint, other);

}

无论如何,我的问题是:可以通过什么方式来完成?我一直在研究这个,但还没有找到一个与我的例子足够相似的例子。如果有人能指导我朝着正确的方向前进,那将非常有用。

这是我用来测试我的方法/类的代码;除了阵列的容量,其他一切都正常。

NIUString s2 = "some text";

cout << "s2: " << s2 << endl;
cout << "s2 size: " << s2.size() << endl;
cout << "s2 capacity: " << s2.capacity() << endl;
cout << "s2 is " << ((s2.empty()) ? "empty\n" : "not empty\n");
cout << endl <<endl << endl;

最佳答案

试试这个,做你想做的:

1) 容量自动填充

2)容量>尺寸

但参数 other 不得使用 new 分配:

template <int _size>
NIUString::NIUString( const char (&other)[_size])
{
Capacity = _size;
Size = strlen(other);

if (Capacity == 0)
{
arrayPoint = nullptr;
}
else
{
arrayPoint = new char[Capacity];
strcpy(arrayPoint, other);
}
}

void main()
{
char aux[20];// this works
strcpy(aux, "test");
NIUString niu(aux);
}

关于c++ - 确定动态内存分配中 char 指针的最大容量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36315253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com