declare fixed size character array on stack c++

风流意气都作罢 提交于 2020-01-13 11:43:33

问题


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;
}

prints

8

How do I allocate a fixed size array (in this case 50 bytes. but it may be any number) on the stack?


回答1:


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

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{};

All of these would print 8 on your platform.

What you need is one of these:

//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;



回答2:


Actually, you are allocating 50 * sizeof(char), or 50 bytes. sizeof(str) is sizeof(char*) which is the size of a pointer.




回答3:


To put a C array on the stack, you must write

char myArray[50] = {0};

The C++ way to do this would be - as Nawaz noted

std::array<char, 50> arr;

But i am not sure if the content of this array will reside on the stack.




回答4:


str here is referencing to an array of characters of size 50*sizeof(char). But sizeof(str) is printing the sizeof of str variable and not the sizeof what it is referencing. str here is just a pointer variable and pointer variable is an unsigned integer whose size is 8.

Also you cannot determine sizeof the reference(In this case, the size of character array). This is because the compiler doesn't know what the pointer is pointing to.

Edit: Getting the sizeof of what the pointer is pointing to doesn't make much sense in C/C++. Suppose a pointer is pointing to a primitive type (like int, long), then you could directly do sizeof(int). And if the pointer is pointing to an array, like in this case, you could directly do arraySize * sizeof(dataTypeOfArray). arraySize is anyways known since C/C++ doesn't allow to define arrays of unknown size, and dataTypeOfArray is anyways known.



来源:https://stackoverflow.com/questions/11938829/declare-fixed-size-character-array-on-stack-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!