本文介绍了在堆栈C上声明固定大小的字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在堆栈上创建一个固定大小的字符数组(它确实需要堆栈分配).我遇到的问题是我无法让堆栈为数组分配8个以上的字节:
I am attempting to create a character array of a fixed size on the stack (it does need to be stack allocated). the problem I am having is I cannot get the stack to allocate more than 8 bytes to the array:
#include <iostream>
using namespace std;
int main(){
char* str = new char[50];
cout << sizeof(str) << endl;
return 0;
}
打印
8
如何在堆栈上分配一个固定大小的数组(在这种情况下为50个字节,但可以是任何数字)?
How do I allocate a fixed size array (in this case 50 bytes. but it may be any number) on the stack?
推荐答案
char* str = new char[50];
cout << sizeof(str) << endl;
它将打印指针的大小,在您的平台上为8
.与这些相同:
It prints the size of the pointer, which is 8
on your platform. It is same as these:
cout << sizeof(void*) << endl;
cout << sizeof(char*) << endl;
cout << sizeof(int*) << endl;
cout << sizeof(Xyz*) << endl; //struct Xyz{};
所有这些都会在您的平台上打印8
.
All of these would print 8
on your platform.
您需要的是其中之一:
//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上声明固定大小的字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!