passing a function a specific array index value - c++

Ive been coding in c and I have an array which is just a char array[22],
I can successfully populate the array with data. there are a few numeric values in the array and i want to check if they fall within a certain range i.e greater than 0 and less than 10 etc.
I have a function, void array_check(testarray[]) declare before the main.
the function is being called inside the main i.e. array_check(testarray[9])
So this should pass the function index number 9, and the function should check if the value of index 9 is between a range etc.
I can't get the program to compile properly. in the function declaration I would have thought the it would be something like this void array_check(testarray[i]) where when I call the function in the main the I would denote the index to check. The compiler tells me that the function decaration and the function itself should have a constant value. It wont allow me to leave the [i] value in the square brackets. any ideas?
thanks guys

If you call check(array[9]), you're just passing the char stored at index 9 in the array, and your function should be declared as
void check(char);
Once you've indexed an array of any type to get the element at that index, there's nothing magically arrayish about the element - it's just a normal object of that type (in this case a char).

Related

Accessing an Element from an int ** array in C++

I am creating a 2D-Array in C++ and need to pass this array as a parameter in a function. In my function, I need to access an element from the array in order to save it as a value, i.e.:
int lowestPoint(int **arr, int x, int y, int n) {
minVal = *(*(arr+x)+y); // here is where I'm getting the exception
return minVal;
}
I've tried setting minVal to arr[X][Y] and have tried to pass the array in as other variations instead of just **arr but nothing seems to be working.
The array is initialized in my main function as int arr[x][y] and I pass it into another function by casting it as otherFunc(reinterpret_cast<int **>((*arr)[n]), n), and then from that function, send it to lowestPoint by calling int val = lowestPoint(arr,i,j,n). I think these calls could be problematic but I'm uncertain how to fix it - I really have no experience with 2D arrays in C++ and it's soo much simpler in Java. I keep getting an EXC_BAD_ACCESS error for the array, so if anyone has any idea how to fix that, I'd really appreciate it. Thanks!
EDIT:
"n" is the size of the array; for example if it's a 3x3 array, n = 3. I just initialized the array as int arr[n][n] and then stored elements. I know the actual array itself represents the correct value, it just can't access it once I send it to another function.
When you pass the array to the first function using reinterpret_cast((*arr)[n]), instead of passing the pointer to the actual array, you are passing the value in location [0][n] (by using (*arr)[n]) and casting it to **arr. So in essence you get a new array that points to a random location in memory that is equal to the content of that array slot.
I am not sure what you intended to do, but if you wanted to pass the actual array, just pass arr. If you planned to pass a sub-array, this method is incorrect altogether as you pass an offset inside an array and you will get skewed data.
Hope This helps,
Lior

Strange parameter recuperation of an array

I am trying to understand some code that passes a multi dimension array to a function. But the prototype of this function intrigues me.
The program creates this "tab" variable:
#define N 8
float tab[N][N];
tab[0][0] = 2; tab[0][1] = 3; tab[0][2] = -1;
tab[1][0] = 3; tab[1][1] = 1; tab[1][2] = -4;
tab[2][0] = 1; tab[2][1] = 2; tab[2][2] = 3;
hello(tab);
And we have this function:
function hello(float mat[][N]) {
I dont understand why the hello function gets the tab variable with an empty [] and then with [N]. What does it change ? I don't understand... Why not tab[][] ?
The code seems to have been made by a good developer so I don't think that the N variable is here for no reason.
If you can explain me this, thanks for your time !
The original code
float tab[N][N];
defines an array of N by N. I'm not going to use row or column because how the array is oriented to the program logic may have no bearing on how the array is represented in memory. Just know that it will be a block of memory N*N long that can be access with mat[0..N-1][0..N-1]. The sizes are known and constant. When you define an array, it must know its size and this size cannot change. If you do not know the size, use a std::vector or a std::vector<std::vector<YOUR TYPE HERE>>
float tab[][];
is illegal because the size of the array is unknown. The compiler has no clue how much storage to allocate to the array and cannot produce a functional (even if flawed) program.
When you pass an array to a function such as
function hello(float mat[][N])
the array decays into a pointer. More info: What is array decaying? Once the array has decayed, the size of the first dimension is lost. To safely use the array you must either already know the size of the array or provide it as another parameter. Example:
function hello(float mat[][N], size_t matLen)
In question, the size is given as N. You know it's N and you can safely call
hello(mat);
without providing any sizing and simply use N inside the function as the bounds. N is not a devious magic number, but it could be given a more descriptive name.
You can also be totally explicit and
function hello(float mat[N][N])
and remove any ambiguity along with the ability to use the function with arrays of size M by N. Sometimes it's a trade-off worth making.
Let me explain a little bit "untechnically", but probably comprehensive:
Think float tab[ROW][COL] as a two dimensional array of floats, where "ROW" stands for the rows, and "COL" stands for the columns, and think that the array is mapped to memory one complete row following the other, i.e.
r0c0,r0c1,r0c2
r1c0,r1c1,r1c2
r2c0,r2c1,r2c2
for ROW=3 and COL=3. Then, if the compiler would have to find out where to write tab[2][1], it would have to take 2 times the size of a row + 1 (where row size is actually the number of columns COL). So for addressing a cell, it is relevant to know the size of the row, whereas within a row one has just to add the column index. Hence, a declaration like tab[][N] is sufficient, as N defines the number of columns - i.e. the size of a row - and lets the compiler address each cell correctly.
Hope it helps somehow.

How do I find the range of this array in c++?

So I'm writing a method where I insert a bunch of numbers into a dynamic array (and increase the size if there's not enough room. I already wrote an insert method that inserts only one value into the array and this method just inserts a bunch of values into the array. It starts out like this:
void dynamic_array::insert(dynamic_array &a, int i) {
Where it takes in a pointer for a dynamic array. The thing is it's easy to figure out how to insert the values but I need to find the range of the numbers that I'm inserting. So given a dynamic array pass by reference, how do I find the range of that array?

Passing 2D array as an argument to a function which takes 1D array

Might sound like a stupid question:
Is it possible to pass 2D array as an argument to a function which takes 1D array
For example:
I have an array players[4][5] and also a function bestCard(), the header for that function looks something like this void bestCard(int arr[5]) <- this 5 is referring to the second dimension of array players
I want to pass players[4][...] in the function bestCard() in a way that the only last dimension is considered to be as an array i.e players[5]
Not sure if my question is comprehensive.
A 2D array is an array of 1D arrays.
In your case, that means player[i] is an array of five elements, for i between 0 and 3. So passing player[i] to your function will pass an array of 5 elements (or more strictly, a pointer to the first element of an array of 5 elements).
I am a beginner at C++, but as far as I know, it would not be possible to pass a 2-d array to your function bestCard(), assuming that you have not overloaded your bestCard() function to take different types of parameters.
Based on the information you have given to me in your question, I am guessing that there are 4 players, and each holds a hand of 5 cards.
If you want to pass bestCard() a single player's hand, you will have to write something like this:
bestCard(players[0]) // Determine the bestCard for the first player.
bestCard(players[1]) // Determine the bestCard for the second player.
...
bestCard(players[3]) // Determine the bestCard for the fourth player.
Even though players is in fact a 2-d array, each of the players[i] (for 0 < i < 4) evaluate to 1-dimensional arrays. Thus, bestCard() ought to be able to accept them as an argument.

How to pass a dynamic 2D array from C++ to C as void *

A function written in C e.g.
extern "C" void cityManipulator( void * data, int size);
takes an array similar to this,
Shanghai, China, 17
Delhi, India, 16
Cairo, Egypt, 7
It then capitalizes the city names and multiplies the population number by a one million.
The function works with the value that I pass not the copy.
The function requires to know the dimensions of the array: how many rows and columns and the size in bytes of each element ( i.e. each city name ) in a given column
I am not interested in how the C function works but I want to use it as is from C++.
The array has to be dynamic i.e. the columns and rows are not static.
How should my data structure that I need to pass to this function look like?
This is my attempt. Use a nested vector of boost::variant
typedef boost::variant<std::string, int> Var;
typedef std::vector<Var> OneRow;
std::vector<OneRow> theArray;
But I can't figure out how to pass theArray to cityManipulator( void *d ).
&theArray[0] does not work.
I wouldn't even attempt to pass an instance of a class to C. My approach would be:
export my data from my C++ classes into a memory suitable for the function to be called
Call the function
import the modified data back to my C++ classes.
Either that, or if the function is trivial, re-implement it in C++.
EDIT: Implementing variable number of elements in a structure in C.
If all you have is access to a single parameter, you cannot pas the number of elements in an array explcitly. In that case, there are two methods you can use.
The first method is flagging the last entry in some manner. The explicit way of doing this is to add a field isLastEntry in the structure, and set it to false in all entries, except the last one. The implicit way of doing it is to allocate a special element, and make it the last entry in the array. Zero terminated strings fall into this category. For complex structures, such as the one provided in npclaudiu's answer, you can add a final dummy field where all pointers are set to NULL as the terminator.
The alternative method is having a structure that contains the length as its first element, and the array as its last. Since C doesn't provide support for variable length arrays, you can use a trick such as the one asked in this question. Simply replace the BYTE type with your structure to handle complex types instead of strings.
You could also try this:
// C++
struct Row {
char* City;
char* Country;
int Population;
};
std::vector<Row> rows;
// Then call your C function like this:
cityManipulator(&rows[0]);