Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declare fixed size character array on stack c++

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?

like image 940
ewok Avatar asked Aug 13 '12 16:08

ewok


1 Answers

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;
like image 84
Nawaz Avatar answered Oct 04 '22 08:10

Nawaz