+ 1
Please someone tell me how to allocate memory to an integer array dynamically without specifying it's size (i.e.not arr [5])
the size of an array must be known only at runtime( should depend on user). I tried out this while(cin>>n) { arr [i++]=n; } but I don't think that the above code is correct please if someone finds the correct ping me so that let me know. thank you
5 Antworten
+ 3
Your best bet would be using the vector template class. It can grow or shrink as needed.
http://en.cppreference.com/w/cpp/container/vector
+ 1
Also it would be much helpful if you provide some other better solution
0
you need to know how big the array must be, so you can allocate the memory needed for it. so your user could for example input a size n and you could use malloc to allocate the appropriate size(i‘m assuming we are talking about c in c++ you of course have to use new). you can not dynamically change the size of an array. if you need that you should use a linked list or another datastructure that can handle dynamic changes of size.
so in c++ for example you can do:
cin >>n;
int *array = new int[n];
to create an array of user specified size
if you do not want to specify a size on creation you can use vector or similar datastructures in c++
0
i dont know c++ but could you use an arraylist.
in java an arraylist is an array class where if it runs out of space it creates a new array that is twice as big and “copies” the values from the old array to the new array in order. thus it has more space
i dont know if that translates to c++ and if it does it still may not work in this case
0
thank you so much for all those who replied me.