Dynamic array | Sololearn: Learn to code for FREE!

0

Dynamic array

I want to know is it possible to have an array without size of it for examle: int x[]; and the size will be the number of input that user enter and we don't know it (I mean dynamic array) please help

11/25/2016 12:47:50 PM

Alireza Nobakht

5 Answers

New Answer

+1

Vector is a template class which can store elements of the same type. vector of ints is declared this way: vector<int> my_vector; Then you can add elements to your vector: int a = 10; my_vector.push_back(a); Accessing elements of the vector is very simple, just like as accessing elements of array: my_vector[0] = 5; //will make first element equal to 5 Vector is very useful and powerful data structure, just google it!

+2

Well, if it is string or character use string data type. It change its size if value is increase. But for double or int. You have to use vector which is dynamic array. You have to define an array size before using.

+1

Which is not possible but you can define the pointer and allocate the memory based on input. like this int *ptr = NULL; //Get the size from user ptr = new int[x]; To access, (ptr + index) = value; // To get value int get = *(ptr + index); Otherwise you can use std::vector, which we can also say dynamic array. Hope this solves your problem.

0

thanks but another question: What is vector and how should i use it?

0

vectors are same as arrays but better