スタック内の動的配列? 質問する

スタック内の動的配列? 質問する

これは正しいですか? これは g++ (3.4) で正常にコンパイルされています。

int メイン()
{
    整数x = 12;
    char pz[x];
}

ベストアンサー1

これらすべての質問を組み合わせた答えは次のとおりです。

あなたのコードは今ない標準C++。標準 C99。これは、C99 では配列をそのように動的に宣言できるためです。明確に言うと、これも標準 C99 です。

#include <stdio.h>

int main()
{
    int x = 0;

    scanf("%d", &x);

    char pz[x]; 
}

これはない標準的なもの:

#include <iostream>

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

std::cin定数の配列サイズが必要なので標準 C++ にはできませんし、C には(または名前空間やクラスなどが)ないので標準 C にもできません。

標準 C++ にするには、次のようにします。

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

動的配列が必要な場合は、できるこれを行う:

#include <iostream>

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

    char *pz = new char[x];

    delete [] pz;
}

しかし、次のようにする必要があります:

#include <iostream>
#include <vector>

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

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

おすすめ記事