Declare an array of fixed-size characters in a C ++ stack

I am trying to create an array of characters of a fixed size on the stack (it should be allocated by stacks). The problem I am facing is that 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 can I allocate an array of a fixed size (in this case, 50 bytes, but can be any number) on the stack?

+4
source share
4 answers
 char* str = new char[50]; cout << sizeof(str) << endl; 

It prints a pointer size that is 8 on your platform. It's the same:

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

All of them will print 8 on your platform.

What you need is one of the following:

 //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; 
+8
source

Actually you allocate 50 * sizeof(char) or 50 bytes. sizeof(str) - sizeof(char*) , which is the size of the pointer.

+8
source

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

Also, you cannot determine the sizeof link (in this case, the size of the character array). This is because the compiler does not know what the pointer points to.

Change Getting the sizeof of what the pointer points to does not make much sense in C / C ++. Suppose the pointer points to a primitive type (e.g. int , long ), then you can directly do sizeof(int) . And if the pointer points to an array, as in this case, you can directly execute arraySize * sizeof(dataTypeOfArray) . arraySize always known, since C / C ++ does not allow you to define arrays of unknown size, and dataTypeOfArray is known anyway.

+1
source

To put an array of C on the stack, you must write

 char myArray[50] = {0}; 

C ++ way to do this would be as Nawaz remarked

 std::array<char, 50> arr; 

But I'm not sure if the contents of this array will be on the stack.

+1
source

All Articles