Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic array in Stack?

Tags:

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

int main()
{
    int x = 12;
    char pz[x]; 
}
like image 418
Janaka Avatar asked Jul 30 '09 04:07

Janaka


People also ask

What is dynamic array with example?

Dynamic arrays are those arrays which are allocated memory at the run time with the help of heap. Thus Dynamic array can change its size during run time. Example- int*temp=new int[100]; thumb_up | 0.

What is a dynamic stack?

Dynamic Stack, just like Dynamic Array, is a stack data structure whose the length or capacity (maximum number of elements that can be stored) increases or decreases in real time based on the operations (like insertion or deletion) performed on it.

What is the concept of dynamic array?

In computer science, a dynamic array, growable array, resizable array, dynamic table, mutable array, or array list is a random access, variable-size list data structure that allows elements to be added or removed. It is supplied with standard libraries in many modern mainstream programming languages.

What is the use of dynamic arrays?

A dynamic array is an array with a big improvement: automatic resizing. One limitation of arrays is that they're fixed size, meaning you need to specify the number of elements your array will hold ahead of time. A dynamic array expands as you add more elements. So you don't need to determine the size ahead of time.


1 Answers

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);
}
like image 187
GManNickG Avatar answered Oct 16 '22 15:10

GManNickG