堆栈中的动态数组? [英] Dynamic array in Stack?

查看:89
本文介绍了堆栈中的动态数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是正确的吗?
这是用g ++(3.4)成功编译的。

 
int main()
{
int x = 12;
char pz [x];
}


解决方案

以下是所有其他答案的组合答案:



您的代码现在是标准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];
}

它不能是标准C ++,因为它需要常量数组大小,标准C,因为C没有 std :: cin (或命名空间或类等等)



要使其成为标准C ++,请执行以下操作:

  int main()
{
const int x = 12; // x is 12 now and forever ...
char pz [x]; // ...因此可以在这里使用
}

数组,您可以执行此操作:

  #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);
}


Is this correct ? This is compiled with g++ (3.4) sucessfully.

int main()
{
    int x = 12;
    char pz[x]; 
}

解决方案

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);
}

这篇关于堆栈中的动态数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆