How do I measure the length of an int array in C++? - c++

My goal is to print all elements of an array of integers regardless of its length. I would like to print it in Python list format, but then I got this error.
Here is my code
int measure(int n[])
{
int num=0;
while (n[num]) { num++; }
return num;
}
void show(int n[])
{
int a = measure(n);
for (int i=0; i<a; i++) {
if (i==0) { printf("[%d,",n[i]); }
else if (i==a-1) { printf(" %d]",n[i]); }
else { printf(" %d,",n[i]); }
}
}
int main(void)
{
int arr[10] = {1,2,3,4,5,6,7,8,9,10};
show(arr);
}
It is supposed to print this: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
but I got this instead: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1935094528, -1664206169]
then I replace show() with this:
int i=0;
while (n[i]) {
if (i==0) { printf("[%d,",n[i]); i++; }
else if (n[i+1] == NULL) { printf(" %d]",n[i]); break; }
else { printf(" %d,",n[i]); i++; }
}
and then I got these:
main.cpp:23:28: warning: NULL used in arithmetic [-Wpointer-arith]
23 | else if (n[i+1] == NULL) { printf(" %d]",n[i]); break; }
| ^~~~
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -680101376, -1228044632]
Why does this happen?

How do I measure the length of an int array in C++?
You can use std::size to get the size of an array with known size:
int arr[10] = {1,2,3,4,5,6,7,8,9,10};
std::cout << std::size(arr);
Why does this happen?
Because the continue condition for your loop is "while the element is not 0". There are no elements with the value 0, so the loop doesn't end before exceeding the end of the array, at which point your overflow the array and the behaviour of the program becomes undefined.
The parameter n of the functions measure and show is not an array of known size. Since n isn't an array of known size, you cannot use std::size to get its size. In fact, although it looks like an array of unspecified size, n is adjusted to be a pointer to element of such array. There is no general way to measure the size of an array given a pointer to its element.
In cases where you want to pass array of any size into a function, and also need to know the size of the array within the function, a good solution is to use a span parameter:
void show(std::span<int> n)

There simply is no "measuring" the length of arrays in C++. You have to know up front, and pass that info to any functions or methods you pass the array to. You can also use a specific "tag" value (as you have implicitly done here) but if you do that, you have to set the tag yourself, and that means you have to know the array length to set the tag. And you must be very sure that the tag does not equal any valid data value in your array.A different approach would be to use std::vector instead of an array. That data type gives you all the functionality of an array but also provides variable length arrays and the ability to inquire the current length.

Related

c++ "push_back" and "pop_back" for array passed by pointer

For context, this for a school assignment. I will attach a picture of the whole question, but to summarize the assignment, we have to make a RECURSIVE maze solver that will return the length of the path to solve the maze from start to finish, but we also have to input the path into an array, which is passed to the array by pointer. As far as I know, I cannot find the size of the array by pointer, and cannot figure out how to put the path into the array.
The question:
Function we have to fill:
int runMaze(Maze& theMaze, int path[], int startCell, int endCell){}
I believe I am properly traversing the maze via DFS and returning the right path length, but I am not sure how to properly input/remove values from the path[].
Is there any way I can know the size of the path[] and be able to push_back() and pop_back() its elements?
This is an example of how our functions are called:
bool test1(std::string& error) {
Maze theMaze("maze1.txt");
int path[10];
int pathLength = runMaze(theMaze, path, 0, 17);
int correctLength = 10;
int correct[10] = { 0, 1, 7, 8, 2, 3, 4, 5, 11, 17 };
bool rc = true;
if (!checkPath(path, pathLength, correct, correctLength)) {
rc = false;
if (pathLength != correctLength) {
error = "Error 1a";
error += ": runMaze() returned ";
error += std::to_string(pathLength);
error += ". It should have returned ";
error += std::to_string(correctLength);
}
else {
error = "Error 1b: runMaze() does not create the correct path\n";
error += "To see what is happening load the corresponding\n";
error += "test and test1path.txt file at: \n";
error += "https://seneca-dsa555-f21.github.io/dsa555-f21/\n";
}
}
printPath("test1path.txt", path, pathLength, 3, 6);
return rc;
}
There are a total of 10 tests it must pass.
Your questions:
Is there any way I can know the size of the path[]
No, there is absolutely no way you can determine the size of a raw array being passed to you without some sort of pre-determined terminator, such as \0 for character arrays.
A raw array as a parameter to a function end up just being a pointer to type. So your parameter is really just int* path, there is no size information included with this.
and be able to push_back() and pop_back() its elements?
There is no push_back() or pop_back() for raw arrays.
I am not sure how to properly input/remove values from the path[]
path[0] = 1;

How to iterate over a pointer to an array (int*) when size is not known?

I was looking through some coding problems and I've come across a problem where the input array is given as "int*" instead of vector.
This made me question how to iterate through this array if we didn't know the size:
vector<int> cellCompete(int* states, int days)
{
// my try:
for (; *states; states++ ) {
cout << *(states) << " ";
}
vector<int> testArray;
return testArray;
}
As you can see i've tried a simple way to iterate over the array, trying to check if the pointer would return nullptr at a point.
Example:
[1, 0, 0, 0, 0, 1, 0, 0] returned "1" as output
[1, 1, 1, 0, 1, 1, 1, 1] returned "1 1 1" as output.
However, this approach worked in the following example:
#include <iostream>
using namespace std;
int main () {
// an array with 5 elements.
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
p = balance;
for (; *p; p++ ) {
cout << *(p) << endl;
}
return 0;
}
This is the question https://www.geeksforgeeks.org/active-inactive-cells-k-days/ but I cannot share the link for where I've come across the question because it is confidential. In the version that I had to solve, the function input was "int*" instead of other options.
Extras:
On the same website, my approach worked for another question with similar input:
int generalizedGCD(int num, int* arr)
{
// WRITE YOUR CODE HERE
for (; *arr; arr++ ) {
cout << *(arr) << " ";
}
return 1;
}
where the input examples were:
[2, 3, 4, 5, 7] and [2, 4, 6, 8, 10]
Is there a more reliable way to iterate through a pointer to an array when we do not know the size of the array?
None of the sources I've found online give a way to iterate without knowing the size.
I wanted to express that this question did indicate the size of the array but it just made me think if there is a way to iterate without given size.
No, there isn't.
You either need to have some kind of a terminating character, like in null-terminated strings or explicitly provide the size.
Besides your approach does not work and is not safe.
*states will not tell you if your pointer is nullptr. operator* is dereferencing and taking value of the object referenced by the pointer. That is why your cycle stops once it hits a 0 value in your array. If you do not have any zeroes in the array, the cycle will go on until going out of the allocated space for you array, and you will have an unaddressable access resulting in undefined behavior, because you will be accessing memory, which could be used for something else, or even worse could be read-only or outside process's address space, causing a crash.
To take the actual value of the pointer (the address), you need to check states instead of *states, but it will not be nullptr. The value of the variable states is just some number(which is equal to the address of the memory where the array is written).

C++ Class, Assigning values during Constructor initialization

I have a 2D array which I declared part of the classes private members. When I call the constructor, I start assigning values to the 2D array. But every time I do so, I'm hit with an error C2059. To make sure nothing else was causing that error I commented out that line and the compiler finished putting together a binary file.
tried:
Variable[row] = { 0, 1, 2, 3};
Variable[row][] = { 0, 1, 2, 3};
Variable[row][4] = { 0, 1, 2, 3};
No luck, any clues. Thanks in advance.
This syntax is only to be used for the creation of the object.
int array[4] = {1, 2, 3, 4};
Once the array is created, you have to use a loop to assign values to it.
Here's a short example :
class A
{
int array[4];
public:
A()
{
// Here, array is already created
// You can _assign_ values to it
}
};
If you want to give it values when it's instantiated in the constructor, the only way is to use initialization lists. Unfortunatly, you can't do this with a static array.
See this this thread.
Unfortunately, we can't yet properly initialize arrays that are members of classes. I don't know exactly how yours is declared, but here's an example of what to do:
class X
{
int Variable[3][4];
public:
X()
{
const int temp[][4] = { { 1, 2, 3, 4}, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
const int sz = sizeof(Variable)/sizeof(**Variable);
std::copy(*temp, (*temp) + sz, *Variable);
}
};
Since your question is not clear enough, all I can do is demonstrating a simple example.
2D array is initialized as,
//you may "optionally" provide the size of first dimension
int arr[][4] = {
{1,2,3,4},
{11,12,13,14},
{21,22,23,24}
};
And is acessed as,
for ( int i = 0 ; i < 3 ; ++i )
{
for ( int j = 0 ; j < 4 ; ++j )
{
cout << arr[i][j] << endl;
}
}
Online demonstration at ideone : http://www.ideone.com/KmwOg
Are you doing similarly?

C++ for_each() and the function pointer

I am try to make the myFunction give me a sum of the values in the array, but I know I can not use a return value, and when I run my program with the code as so all I get is a print out of the values and no sum why is that?
void myFunction (int i) {
int total = 0;
total += i;
cout << total;
}
int main() {
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for_each( array, array+10, myFunction);
return 0;
}
You really need a functor to store state between iterations:
struct Sum
{
Sum(int& v): value(v) {}
void operator()(int data) const { value += data;}
int& value;
};
int main()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int total = 0;
std::for_each( array, array+10, Sum(total));
std::cout << total << std::endl;
}
When you declare a variable (i.e. int total) it exists for the duration of its scope (usually equivalent to the nearest surrounding pair of { and }. So, in your function myFunction, total ceases to exist when the function returns. It returns once per call--once per element in your array, that is. In order to actually sum its values (or otherwise preserve a variable beyond the end of myFunction, you must give it a broader scope.
There are two relevant ways to do this. One is a "good" way, and one is an "easier-but-badly-styled" way. The good way involves a functor or context object--#Martin has already posted an example. The "bad" way is marking int total as static. It'll work the first time you use it, if your code is single-threaded... and then never again. If somebody suggests it... don't do it. :)
total is a variable with automatic storage duration. Every time myFunction() is called, a new total is created and initialized to 0. You could:
give total static storage duration (with the static keyword), but you won't be able to assign its value to anything, because it is still local scope. A bad idea if you want to reuse this function, anyhow.
make total a global variable. Also a bad idea if you want to reuse this function
make a "functor", as described in Martin York's answer. This is the most reusable implementation
But, my chosen solution is "you're asking the wrong question" and you should be using std::accumulate():
#include <iostream>
#include <numeric>
int main() {
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int total = std::accumulate(array, array+10, 0);
std::cout << total << '\n';
return 0;
}
Your total is local at each function call. It's initialized with 0 at every iteration. You could just declare it global (or pack into a parameter, etc.)
myFunction is being called each time and total is local to the function... try marking total as static instead:
static int total = 0
You need to make the total persistent across function calls. You also need to access the result separately from adding the intermediate results to it, which rules out (at least straightforward use of) a function at all -- you really need a class instead.
The total is a local variable. It will be destroyed once the myFunction finished processing one data.
The typical way to have a state is to make myFunction a function object (a struct that overloads the () operator).
The dirty way is to make total a global variable.
In your case I'd recommend you use the accumulate function instead (assuming that cout << total is just for debugging).
You reset the value of 'total' to 0 each time you call the function.
Declare it 'static'
void myFunction (int i) {
static int total = 0;
total += i;
cout << total;
}
EDIT:
Alternatively, if you want to access the value of 'total' later, you will need to either use a global variable (of some kind! Could be in a class or functor! don't flame me!), or just use a for loop, and pass it in as a pointer (i.e., not use for_each):
void myFunction (int i, int * p_total) {
//No initialization
*p_total += i;
cout << *p_total;
}
int main() {
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int total = 0;
for(int i = 0; i < 10, i++)
myFunction(array[i], &total);
//total is now 55
return 0;
}
Note: I'm a C programmer trying to learn C++. This is how I would do it (which is very C-like), it might not be the standard C++ way.

What is the easiest way to set the value of an entire array?

My current project requires me to fill an array based upon some other values. I know there's the shortcut:
int arr[4][4] = { {0,0,0,0} , {0,0,0,0} , {0,0,0,0} , {0,0,0,0} };
But in this case, I need to fill the array after its declaration. I currently have my code formatted like this:
int arr[4][4];
if(someothervariable == 1){
arr = { {1,1,1,1},
{1,2,3,4},
{2,,3,4,5},
{3,4,5,6} };
}
But it won't compile. Is there a way to make use of the mentioned shortcut in my case? If not, whats the best fix available? I'd appreciate a way to set it without explicitly assigning each element? ie: arr[0][0] = ...
How about using std::copy() ?
int arr[4][4];
if(someothervariable == 1){
const static int a2[4][4] = { {1,1,1,1},
{1,2,3,4},
{2,3,4,5},
{3,4,5,6} };
std::copy(&a2[0][0], &a2[0][0]+16, &arr[0][0]);
}
No, array initialization syntax is for array initialization. Although, you can use memset if all the values are the same byte.
The boost.assign library adds some interesting syntax for modifying/filling collections, but AFAIK it doesn't support C style arrays (only C++ and Boost containers).
In the current version of C++ language the only way to do it is to copy it from some original
int arr[4][4];
if (someothervariable == 1)
{
const int SOURCE[4][4] = // make it `static` if you prefer
{
{1, 1, 1, 1},
{1, 2, 3, 4},
{2, 3, 4, 5},
{3, 4, 5, 6}
};
assert(sizeof arr == sizeof SOURCE); // static assert is more appropriate
memcpy(&arr, &SOURCE, sizeof arr);
}
The source "constant" can be declared as static in order to avoid re-initialization, if the compiler is not smart enough to optimize it by itself.
In the future version of the language a feature similar to C's compound literals is planned, which will provide support for immediate initialization (basically what you tried to do in your original post).
If you wish to fill the array with a single value:
#include<algorithm>
#include<vector>
// ...
std::vector<int> arr;
std::fill(arr.begin(), arr.end(), VALUE); // VALUE is an integer
If you wish to calculate the value for each element:
struct get_value {
int operator()() const { /* calculate and return value ... */ }
};
std::generate(arr.begin(), arr.end(), get_value());
If you are setting everything to the same value (such as zero), you may be able to get away with ...
memset (arr, 0, sizeof (arr));
Note that this is fraught with perils. You have to know your type sizes and all that jazz.
However, it appears that that will not suffice for you. If you want to fill the array with different values, I can only only think of two ways of doing this.
Method #1. (Can be a pain the butt)
arr[0][0] = 1;
...
arr[0][3] = 1;
arr[1][0] = 1;
...
arr[1][3] = 4;
arr[2][0] = 2;
...
arr[2][3] = 5;
arr[3][0] = 3;
...
arr[3][3] = 6;
Method #2.
Predefine a set of arrays and switch between them using a pointer;
int arr1[4][4] = {
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0} };
int arr2[4][4] = {
{1,1,1,1},
{1,2,3,4},
{2,,3,4,5},
{3,4,5,6} };
int *arr[4];
Now you only have the four (4) values of *arr[] to set instead of setting everything. Of course, this really only works if your arrays will be filled with predetermined constants.
Hope this helps.
I'm not sure if I like this solution or not, but C/C++ will give you assignment convenience if you wrap the array inside a struct with the minor cost of then having to use the struct name to get at the array:
typedef struct {
int data[4][4];
} info_t;
info_t arr;
if (someothervariable == 1){
static const info_t newdata = {{ // since this is static const, there generally
// won't be a copy - that data will be 'baked'
// into the binary image (or at worst a
// single copy will occur)
{1,1,1,1},
{1,2,3,4},
{2,3,4,5},
{3,4,5,6}
}};
arr = newdata; // easy to assign new data to the array
}
int somethingelse = arr.data[1][2]; // a tiny bit less convenient to get
// to the array data
int arr[4][4];
if (someothervariable == 1) {
int tmp[4][4] = { {1, 1, 1, 1}, {1, 2, 3, 4}, {2, 3, 4, 5}, {3, 4, 5, 6} };
arr = tmp;
}