declare fixed size character array on stack c++
Solution 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;
Solution 2
Actually, you are allocating 50 * sizeof(char)
, or 50 bytes. sizeof(str)
is sizeof(char*)
which is the size of a pointer.
Solution 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.
Solution 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.
ewok
Software engineer in the Greater Boston Area. Primary areas of expertise include Java, Python, web-dev, and general OOP, though I have dabbled in many other technologies.
Updated on June 21, 2022Comments
-
ewok about 2 years
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?