Dynamic array in Stack?

Here’s your combination answer of all these other ones:

Your code right now is not standard C++. It is standard C99. This is because C99 allows you to declare arrays dynamically that way. To clarify, this is also standard C99:

#include <stdio.h>

int main()
{
    int x = 0;

    scanf("%d", &x);

    char pz[x]; 
}

This is not standard anything:

#include <iostream>

int main()
{
    int x = 0;
    std::cin >> x;
    char pz[x]; 
}

It cannot be standard C++ because that required constant array sizes, and it cannot be standard C because C does not have std::cin (or namespaces, or classes, etc…)

To make it standard C++, do this:

int main()
{
    const int x = 12; // x is 12 now and forever...
    char pz[x]; // ...therefore it can be used here
}

If you want a dynamic array, you can do this:

#include <iostream>

int main()
{
    int x = 0;
    std::cin >> x;

    char *pz = new char[x];

    delete [] pz;
}

But you should do this:

#include <iostream>
#include <vector>

int main()
{
    int x = 0;
    std::cin >> x;

    std::vector<char> pz(x);
}

Leave a Comment