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

ewo*_*wok 4 c++ stack memory-management

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

#include <iostream>
using namespace std;

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

        return 0;
}
Run Code Online (Sandbox Code Playgroud)

版画

8
Run Code Online (Sandbox Code Playgroud)

如何在堆栈上分配固定大小的数组(在这种情况下为50个字节但可能是任何数字)?

Naw*_*waz 8

char* str = new char[50];
cout << sizeof(str) << endl;
Run Code Online (Sandbox Code Playgroud)

它打印指针的大小,该指针8位于您的平台上.它们与以下相同:

cout << sizeof(void*) << endl;
cout << sizeof(char*) << endl;
cout << sizeof(int*) << endl;
cout << sizeof(Xyz*) << endl;  //struct Xyz{};
Run Code Online (Sandbox Code Playgroud)

所有这些都将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;
Run Code Online (Sandbox Code Playgroud)


Vla*_*anu 8

实际上,你正在分配50 * sizeof(char),或50个字节.sizeof(str)sizeof(char*)指针的大小.