gpt4 book ai didi

c++ - 在堆栈上声明固定大小的字符数组 C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:57:27 25 4
gpt4 key购买 nike

我正在尝试在堆栈上创建一个固定大小的字符数组(它确实需要分配堆栈)。我遇到的问题是我无法让堆栈为数组分配超过 8 个字节:

#include <iostream>
using namespace std;

int main(){
char* str = new char[50];
cout << sizeof(str) << endl;

return 0;
}

打印

8

如何在堆栈上分配一个固定大小的数组(在本例中为 50 个字节。但它可以是任何数字)?

最佳答案

char* str = new char[50];
cout << sizeof(str) << endl;

它打印指针的大小,在您的平台上为 8。它与这些相同:

cout << sizeof(void*) << endl;
cout << sizeof(char*) << endl;
cout << sizeof(int*) << endl;
cout << sizeof(Xyz*) << endl; //struct Xyz{};

所有这些都会在您的平台上打印 8

您需要的是以下之一:

//if you need fixed size char-array; size is known at compile-time.
std::array<char, 50> arr;

//if you need fixed or variable size char array; size is known at runtime.
std::vector<char> arr(N);

//if you need string
std::string s;

关于c++ - 在堆栈上声明固定大小的字符数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11938829/

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