What's the correct way to work with bounded arrays in C++? - c++

I'm trying to understand how bounded arrays work in C++. I need to have a quick length method to return the size of my bounded array. In Java I would do something like that:
int[] array = new int[10];
System.out.println(array.length); // 10
System.out.println(array[5]); // 0
array[5] = 11;
System.out.prinltn(array[5]); // 11
If possible I would like to use an object array (i.e. a class implementing an array functionality) instead of pointers. Would I be correct to say that it feels much more natural to use an object array instead of a memory pointer to work with arrays?

C++ has a class std::array<type, size> which is basically just a wrapper for stack-allocated arrays. C++ also has a class std::vector<type> which is a wrapper for heap-allocated arrays (like what you're used to in Java) but which also has ArrayList-like functionality.
In your case, writing code which is logically and semantically identical to yours is:
std::vector<int> array(10, 0); //EDIT: I added the second parameter because I don't think all implementations zero the memory when allocating it. This ensures that the memory is zeroed before use, like it would be in Java.
std::cout << array.size() << std::endl;
std::cout << array[5] << std::endl;
array[5] = 11;
std::cout << array[5] << std::endl;
Though, I wouldn't name the variable array, since that could be confusing.

Related

How to increase size of pointer array when code is running c++

Let's say I declared a pointer array like this
Animal** animalsarr = new Animal*[10];
If in this array, x babies were born and I want to resize it to new Animal*[10+x] while it's running, how can I do it?
C++ is created to make developing easier. It has a really nice standard library containing a type called std::vector that does exactly what you want:
std::vector<std::unique_ptr<Animal>> v;
v.push_back(nullptr);
v.push_back(std::make_unique<Fish>());
// ...
std::cout << "Elements in use: " << v.size() << std::endl;
Note: std::vector::resize allows you to grow/shrink the vector, however, I have the feeling you actually don't need that at the moment.
there are at least two ways:
Manually create new array (Animal** animalsarr_2 = new
Animal*[10+x]);, move all content from existing animalsarr to
animalsarr_2, then delete animalsarr
Use containers which does all these stuff for you. For example std::vector:
std::vector<Animal*> animalsarr;
animalsarr.resize(10);
then when needed, just increase vector size:
animalsarr.resize(10+x);

Pass array to function without so it would not change original array no matter what

I have a function that performs some magic on the array that I am passing. But the original array should be intact. Unfortunately it is changing its content based on what is happening in the array.
Can you help me, please?
Function:
void test(int* array) {
array[0] = 1; // EDIT: Added missing line
std::cout << "Inside: " << array[0] << endl;
}
int main() {
int *testArray = new int[1];
testArray[0] = 0;
std::cout<<testArray[0]<<endl;
test(testArray);
std::cout << "Outside: " << testArray[0] << endl;
}
Current result is:
0
Inside: 1
Outside: 1
Result I would want to have:
0
Inside: 1
Outside: 0
Is this possible?
It sounds like you want to pass array by value not by reference. You are passing pointer to a first element here. So, any changes which you perform to that array inside that function will be reflected to original array.
The other problem is you haven't posted fair amount of code regarding the problem you want to solve. I am assuming you want functionality like this.
See live demo here.
#include <iostream>
void test(const int* array) {
array[0]=1;
std::cout << "Inside: " << array[0] << std::endl;
}
int main() {
int *testArray = new int[1];
testArray[0] = 0;
std::cout<<testArray[0]<<std::endl;
test(testArray);
std::cout << "Outside: " << testArray[0] << std::endl;
delete[] testArray;
}
Compiler will give you following errors:
Error(s):
source_file.cpp:4:13: error: read-only variable is not assignable
array[0]=1;
~~~~~~~~^
1 error generated.
You should not use new[] to allocate dynamic arrays in C++. 99% of the time you should be using std::vector If you want dynamic array in C++.
Avoid using C compatibility features...
void test( std::array<int, 1> a )
{
a[0] = 1; // fine
std::cout << "Inside: " << a[0] << endl;
};
int main()
{
std::array<int, 1> testArray;
testArray[0] = 0;
std::cout<<testArray[0]<<endl;
test(testArray);
std::cout << "Outside: " << testArray[0] << endl;
}
If you need the size determined at runtime, use std::vector instead of std::array.
EDIT: As others have pointed out, it seems like you want to either pass the array by value instead of by reference, thus copying the elements of the array and modifying only the copy, or you want to avoid modifying any part of the array altogether. I'll elaborate on both parts a bit more:
In C++, there is near to no distinction between arrays and pointers. Note that both your variable testArray and your parameter array are pointers to the beginning of an array. If you use array to modify any part of the underlying array, what you actually do is modify the memory are that is described by both testArray and array. If you don't want to modify any part of the array at all, it would be helpful to use the const qualifier, as Destructor already wrote in his answer. If you however want to keep the original array but still want to make some modifications inside the function, the following still applies:
To keep the array from being modified, the only general way that works is to copy all of its elements by creating a new array of the same size, copying all elements from the input array to the copy and then working only on the copy, which should be deleted after the function has finished.
My personal answer:
I would recommend that you look into some of C++'s data structures, especially std::vector. If you pass it by value (not by reference), vector takes care of all the necessary copy operations I just described and in all cases, you can use it in the same way as an array, while it provides lots of additional features (i.e. dynamic size, deletion and insertion of elements, simplified iteration, ...).

generate multidimensinal array instead of cout

I have this main function and i want to get an multidimensional array out of this to generate a graph instead of cout
int main(){
zoro z;
std:ifstream k("ggg.grf");
z.getfromstream(k);
for(int i =0 ; i < z.nnodes; i++){
edge_iteratore s = z.begin(i);
while(s != z.end(i)){
std:cout << "(" << (*s).height << "," << (*s).weight << ")" << std::endl;
++s;
}
}
return 0;
}
I' trying to get std::out to a function to generate a multidimensional array
so i have implemented this function to get an array,
int createarr(height,width){
int** ary = new int*[height];
for(int i = 0; i < height; ++i)
ary[i] = new int[weight];
}
but nothing works, how can i return an multidimensional array to use it in another function call instead of outputting it to the screen.
If height and weight are constexpr values you know at compile time, declare std::array<<std::array<int>, weight>, height>. This gets you locality of reference. If they are values you compute at runtime or that could vary, use vector<vector<int>>(height) and initialize each row. Then the compiler takes care of freeing the memory for you. If only one is fixed, you can also do a vector of arrays or an array of vectors.
It’s unfortunate that, because of the legacy char** argv interface of main(), every beginning C and C++ programmer thinks that’s how you do a two-dimensional array. A ragged array like that is almost never what you really want. But if you do, use std::vector to manage the memory for you.
The problem with your createarr() as written is that it doesn’t return any array pointer, but RAII is more likely what you want. And if you do have a sparse matrix that would benefit from raggedness, you can use a format like Compressed Sparse Row.
You need to return a pointer to the created array.
But you'll need to somehow deal with the fact that this is dynamically allocated memory, ie, you need to release it when you're done.
And you'll need to somehow encapsulate the dimensions too, which then means it needs to be a struct.
When you finally get tired of dealing with memory leaks, and understand how pointers work, use std::vector like the other guy said.
In the meantime, don't try to implement complicated algorithms in C without understanding the basics first. Brush up hard on how pointers and arrays actually work, first.

c++ understanding size_t behaviour for vector creation

this is a folow up to this https://softwareengineering.stackexchange.com/questions/256241/c-coding-practice-class-vs-free-functions question I posted a few day ago. In short, the idea is to create a custom vector class for statistical data analysis.
I got a great response, that made me realise that I need to understand: why use size_t in a constructor of a container class and why use it anyway?
Here is a part of the proposed solution:
template<class T>
class vect
{
std::vector<T> m;
public:
vect(size_t n) :m(n) {}
void addTo(T a){ m.push_back(a); }
std::vector<T> get() const { return m;}
... more functions and overloaded operators
};
I understand that size_t is an (unsigned int) data type and should be used to indicate that it's value should represent the size of n object.
In order to understand the behaviour of size_t I did the following:
int main() {
vect<int> m(0);
vect<int> n(100);
std::cout << sizeof(n) << std::endl;
std::cout << sizeof(m) << std::endl;
std::cout << sizeof(m.get()) << std::endl;
for (int i = 0 ; i < 100; i++) {
m.addTo(i);
}
std::cout << sizeof(m) << std::endl;
std::cout << sizeof(m.get()) << std::endl;
}
all of which return "24". (I expected a change in the size of the object after adding parameters to it.) However:
for(int i = 0; i<100;i++)
std::cout << m[i] << std::endl;
nicely prints out all values from 0 to 100. Thus I know that there are 100 integers stared in the vector, but then why is its size 24 and not 100?
Obviously I am new to c++ programming and to make things worse this is my first template class.
Thank you for your time and patience, I really appreciate it.
sizeof is concerned with the size of a type in memory. Your vect class is a type that takes up 24 bytes. The size of a type never changes once it's been compiled.
But how can your vector store so much information without changing it size? Because it contains pointers to other things that can take up much more space (indeed, they can take up as much space as you need - that's why they're called dynamic data structures). Presumably your vect instance contains a pointer to the standard vector class, which contains other pointers, maybe to an array or a dynamically allocated section of memory which holds the actual data.
You cannot query the size of those private, indirectly referenced bits of memory because you don't know their name, or their type. In fact, a major reason for creating such container classes is so that you don't have to know how much memory to allocate - you just stuff things into them, and they silently allocate as much memory as necessary.

Can I determine the size/length of an array in C++ without having to hardcode it?

I am basically looking for some sort of "dynamic" way of passing the size/length of an array to a function.
I have tried:
void printArray(int arrayName[])
{
for(int i = 0 ; i < sizeof(arrayName); ++i)
{
cout << arrayName[i] << ' ';
}
}
But I realized it only considers its bytesize and not how many elements are on the array.
And also:
void printArray(int *arrayName)
{
while (*arrayName)
{
cout << *arrayName << ' ';
*arrayName++;
}
}
This has at least printed me everything but more than what I expected, so it doesn't actually work how I want it to.
I reckon it is because I don't exactly tell it how big I need it to be so it plays it "safe" and throws me some big size and eventually starts printing me very odd integers after my last element in the array.
So I finally got this work around, yet I believe there is something better out there!:
void printArray(int *arrayName)
{
while (*arrayName)
{
if (*arrayName == -858993460)
{
break;
}
cout << *arrayName << ' ';
*arrayName++;
}
cout << '\n';
}
After running the program a few times I realized the value after the last element of the array that I have input is always: -858993460, so I made it break the while loop once this value is encountered.
include <iostream>
include <conio.h>
using namespace std;
// functions prototypes
void printArray (int arrayName[], int lengthArray);
// global variables
//main
int main ()
{
int firstArray[] = {5, 10, 15};
int secondArray[] = {2, 4, 6, 8, 10};
printArray (firstArray,3);
printArray (secondArray,5);
// end of program
_getch();
return 0;
}
// functions definitions
void printArray(int arrayName[], int lengthArray)
{
for (int i=0; i<lengthArray; i++)
{
cout << arrayName[i] << " ";
}
cout << "\n";
}
Thank you very much.
TL;DR answer: use std::vector.
But I realized it [sizeof()] only considers its bytesize and not how many elements are on the array.
That wouldn't be a problem in itself: you could still get the size of the array using sizeof(array) / sizeof(array[0]), but the problem is that when passed to a function, arrays decay into a pointer to their first element, so all you can get is sizeof(T *) (T being the type of an element in the array).
About *arrayName++:
This has at least printed me everything but more than what I expected
I don't even understand what inspired you to calculate the size of the array in this way. All that this code does is incrementing the first object in the array until it's zero.
After running the program a few times I realized the value after the last element of the array that I have input is always: -858993460
That's a terrible assumption and it also relies on undefined behavior. You can't really be sure what's in the memory after the first element of your array, you should not even be accessing it.
Basically, in C++, if you want to know the size of a raw array from within a function, then you have to keep track of it manually (e. g. adding an extra size_t size argument), because of the way arrays are passed to functions (remember, they "decay into" a pointer). If you want something more flexible, consider using std::vector<int> (or whatever type of objects you want to store) from the C++ standard library -- it has a size() method, which does exactly what you want.
1st try
When arrays are passed into functions they decay to pointers. Normally, using sizeof on an array would give you its size in bytes which you could then divide by the size in bytes of each element and get the number of elements. But now, since you have a pointer instead of an array, calling sizeof just gives you the size of the pointer (usually 4 or 8 bytes), not the array itself and that's why this fails.
2nd try
The while loop in this example assumes that your array ends with a zero and that's very bad (unless you really did use a zero as a terminator like null-terminated strings for example do). If your array doesn't end with a zero you might be accessing memory that isn't yours and therefore invoking undefined behavior. Another thing that could happen is that your array has a zero element in the middle which would then only print the first few elements.
3rd try
This special value you found lurking at the end of your array can change any time. This value just happened to be there at this point and it might be different another time so hardcoding it like this is very dangerous because again, you could end up accessing memory that isn't yours.
Your final code
This code is correct and passing the length of the array along with the array itself is something commonly done (especially in APIs written in C). This code shouldn't cause any problems as long as you don't pass a length that's actually bigger than the real length of the array and this can happen sometimes so it is also error prone.
Another solution
Another solution would be to use std::vector, a container which along with keeping track of its size, also allows you to add as many elements as you want, i.e. the size doesn't need to be known at runtime. So you could do something like this:
#include <iostream>
#include <vector>
#include <cstddef>
void print_vec(const std::vector<int>& v)
{
std::size_t len = v.size();
for (std::size_t i = 0; i < len; ++i)
{
std::cout << v[i] << std::endl;
}
}
int main()
{
std::vector<int> elements;
elements.push_back(5);
elements.push_back(4);
elements.push_back(3);
elements.push_back(2);
elements.push_back(1);
print_vec(elements);
return 0;
}
Useful links worth checking out
Undefined behavior: Undefined, unspecified and implementation-defined behavior
Array decay: What is array decaying?
std::vector: http://en.cppreference.com/w/cpp/container/vector
As all the other answers say, you should use std::vector or, as you already did, pass the number of elements of the array to the printing function.
Another way to do is is by putting a sentinel element (a value you are sure it won't be inside the array) at the end of the array. In the printing function you then cycle through the elements and when you find the sentinel you stop.
A possible solution: you can use a template to deduce the array length:
template <typename T, int N>
int array_length(T (&array)[N]) {
return N;
}
Note that you have to do this before the array decays to a pointer, but you can use the technique directly or in a wrapper.
For example, if you don't mind rolling your own array wrapper:
template <typename T>
struct array {
T *a_;
int n_;
template <int N> array(T (&a)[N]) : a_(a), n_(N) {}
};
You can do this:
void printArray(array<int> a)
{
for (int i = 0 ; i < a.n_; ++i)
cout << a.a_[i] << ' ';
}
and call it like
int firstArray[] = {5, 10, 15};
int secondArray[] = {2, 4, 6, 8, 10};
printArray (firstArray);
printArray (secondArray);
The key is that the templated constructor isn't explicit so your array can be converted to an instance, capturing the size, before decaying to a pointer.
NB. The wrapper shown isn't suitable for owning dynamically-sized arrays, only for handling statically-sized arrays conveniently. It's also missing various operators and a default constructor, for brevity. In general, prefer std::vector or std::array instead for general use.
... OP's own attempts are completely addressed elsewhere ...
Using the -858993460 value is highly unreliable and, in fact, incorrect.
You can pass a length of array in two ways: pass an additional parameter (say size_t length) to your function, or put a special value to the end of array. The first way is preferred, but the second is used, for example, for passing strings by char*.
In C/C++ it's not possible to know the size of an array at runtime. You might consider using an std::vector class if you need that, and it has other advantages as well.
When you pass the length of the array to printArray, you can use sizeof(array) / sizeof(array[0]), which is to say the size in bytes of the whole array divided by the size in bytes of a single element gives you the size in elements of the array itself.
More to the point, in C++ you may find it to your advantage to learn about std::vector and std::array and prefer these over raw arrays—unless of course you’re doing a homework assignment that requires you to learn about raw arrays. The size() member function will give you the number of elements in a vector.
In C/C++, native arrays degrade to pointers as soon as they are passed to functions. As such, the "length" parameter has to be passed as a parameter for the function.
C++ offers the std::vector collection class. Make sure when you pass it to a function, you pass it by reference or by pointer (to avoid making a copy of the array as it's passed).
#include <vector>
#include <string>
void printArray(std::vector<std::string> &arrayName)
{
size_t length = arrayName.size();
for(size_t i = 0 ; i < length; ++i)
{
cout << arrayName[i] << ' ';
}
}
int main()
{
std::vector<std::string> arrayOfNames;
arrayOfNames.push_back(std::string("Stack"));
arrayOfNames.push_back(std::string("Overflow"));
printArray(arrayOfNames);
...
}