Listing Arrays in C - c

I'm learning C . I want to list an array's values.
In PHP :
$arr = array("laguna", "megane", "clio");
foreach($arr as $no => $name)
{
echo $no." ) ".$name;
}
/*
Output :
0) Laguna
1) Megane
2) Clio
*/
How can i do it in C?

In C
char* arr[] = {"laguna","megane","clio",NULL};
for( int i = 0; arr[i]; i++)
{
printf("%d) %s\n",i,arr[i]);
}

NOTE: The OP's question was originally tagged as C++, so I'll leave this answer as-is for those who might be curious about a C++ specific method
You can use the for_each algorithm inside of algorithm ... it works with any object that can be dereferenced and incrementally interated (i.e., supports operator++).
The input arguments to the for_each algorithm are a pointer (or iterator) that points to the start of the array or container object if you're using STL containers like std::vector, etc., a pointer or iterator that points to one past the end of the object, and then a function that will be applied to each member of the array or container.
For instance:
#include <algorithm>
#include <iostream>
using namespace std;
int array[] = { 1, 2, 3, 4, 5 };
//pointer to the start of the array
int* start = array;
//pointer to one position past the end of the array
int* end = array + sizeof(array)/sizeof(int);
//function applied to each member of the array
void function(int a)
{
static int count = 0;
cout << "Value[" << count++ << "]: " << a << endl;
}
//call the for_each algorithm
for_each(start, end, function);

#include <stdio.h>
int main(){
char *arr[] = {"laguna", "megane", "clio", NULL};
char **name = arr;
while(*name){
int no = name - arr;
printf("%d ) %s\n", no, *name++);
}
return 0;
}

C and C++ are not the same language. Using C++ std::vector in a recent C++ dialect, you might try (untested code):
std::vector<std::string> vecstr;
vecstr.push_back("laguna");
vecstr.push_back("megane");
for (std::vector<std::string>::iterator it= vecstr.begin();
it != vecstr.end(); it++)
std::out << *it << std::endl;

This will give you a good look at using arrays in c++ .
// arrays example
#include <iostream>
using namespace std;
int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += billy[n];
}
cout << result;
return 0;
}
You can go one step ahead and use STL containers like set and map.
http://ideone.com/U62Q8

In c:
#include <stdio.h>
int array[6]= { 1, 2, 3, 4, 5, 6 };
void main() {
int len=sizeof(array)/sizeof(int);
int i;
for(i=0;i<len;i++)
{
printf("Elements in position :%d :%d ",i,array[i]);
}
}

Related

How to traverse a 2D array using recursion

I'm looking for someone to help me to traverse and display the 2d array or matrix using recursion.
void display(int** matrix1,int row, int column)
This is what I am doing for the 1D array:
void print_array(int arr[], int size, int i)
{
if (i == size) {
cout << endl;
return;
}
cout << arr[i] << " ";
print_array(arr, size, i+1);
}
I know how to traverse 1D array but unable to do this.
I want to display each element in the matrix using recursion.
First of all, it is not quite clear why you want a recursive solution. Perhaps it is a matter of tase, but I find recursion difficult to write, read and debug. Anyhow, I allowed myself to modify your 1d version:
#include <iostream>
#include <vector>
void print_array(const std::vector<int>& arr,size_t i = 0) {
if (i == arr.size()) {
std::cout << '\n';
return;
}
std::cout << arr[i] << " ";
print_array(arr, i+1);
}
I use size_t instead of int, because thats the type to be used when comparing with a containers size. I supplied a default for i because when you call it you dont want to pass the index, but just print the whole array. std::endl is not only printing a new line, but it also flushes the stream. This is unnecessary in most cases.
For the 2D case all you need to add is a second index and a condition to go to the next row.
That is, if the signature of the function is
void print_array(const std::vector<std::vector<int>>& arr,size_t i=0,size_t j=0)
and it prints arr[i][j] then you need to return without printing anything when i == arr.size() and you have to skip to the next row when j== arr[i].size(). This can be done with a condition along the line of:
if (j == arr[i].size()) {
std::cout << '\n';
print_array( arr, i+1,0); // start with the first element of next row
return;
}
PS is you insist on a int**, it should be straightforward to adapt, but I would strongly suggest to use a vector and perhaps even a std::vector<std::array> if the inner arrays all have same size.
I am sure that you need to write a C program or a C++ program but using functionality of C due to your declaration of "2D array" like int **.:)
The function can be easy implemented if to use one more auxiliary recursive function.
Here is a demonstrative program
#include <stdio.h>
void display_row( int *a, size_t column )
{
column == 0 ? ( void )putchar( '\n' )
: ( void )( printf( "%2d ", *a ), display_row ( ++a, --column ) );
}
void display( int **a, size_t row, size_t column )
{
if ( row != 0 )
{
display_row( *a, column );
display( ++a, --row, column );
}
}
int main(void)
{
enum { M = 3, N = 4 };
int a1[N] = { 1, 2, 3, 4 };
int a2[N] = { 5, 6, 7, 8 };
int a3[N] = { 9, 10, 11, 12 };
int *a[M] = { a1, a2, a3 };
display( a, M, N );
return 0;
}
The program output is
1 2 3 4
5 6 7 8
9 10 11 12
If not to use an auxiliary function then another approach is to use a static variable inside the recursive function.
Here is a demonstrative program that uses a recursive function with a static variable.
#include <stdio.h>
void display( int** a, size_t row, size_t column )
{
static size_t pos = 0;
if ( row != 0 && column == 0 )
{
putchar( '\n' );
size_t tmp = column;
column = pos;
pos = tmp;
--row;
++a;
}
if ( row )
{
printf( "%2d ", a[0][pos++] );
display( a, row, --column );
}
}
int main(void)
{
enum { M = 3, N = 4 };
int a1[N] = { 1, 2, 3, 4 };
int a2[N] = { 5, 6, 7, 8 };
int a3[N] = { 9, 10, 11, 12 };
int *a[M] = { a1, a2, a3 };
display( a, M, N );
return 0;
}
Its output is the same as shown above.
If you need a C++ program then just include headers
#include <iostream>
#include <iomanip>
and instead of for example this call of printf
printf( "%2d ", a[0][pos++] );
use
std::cout << std::setw( 2 ) << a[0][pos++];
Here is a simple recursive solution hope you can understand............
#include <iostream>
using namespace std;
void print(int x,int y,int arr[3][3])
{
cout<<arr[x][y]<<" ";
if(x==2 && y==2)//Its a 3 by 3 matrix.....Index starts from 0 and ends at 2 for both row and colomn.
{
return;
}
else if(y==2)
{
cout<<endl;
print(x+1,0,arr);
}
else
print(x,y+1,arr);
}
int main()
{
int arr[3][3]={{1,2,3},{4,5,6},{7,8,9}};
print(0,0,arr);
return 0;
}

How to perform A-B set operation in C program using builtin library

I am new to C language. Suppose I have two arrays a and b
int a[10] = { 1,2,3,4,5,6,7,8,9,0 };
int b[10] = { 1,3,5,7,9 };
and I want to perform a-b so that I can get all elements of array a which are not present in array b. In ruby or python, I can just simply do a-b and get the result. Here is my c code that I have tried but my code which is not working.I am looking for a C library that does this operation for me in a line.I have also found this library but not sure how to implement it. Any kind of help is appreciated.
#include<stdio.h>
#define Max 100
int m,n,i,j,k,p,q,r,s;
int flag=1;
char char1,char2,char3;
void Difference(int *,int *,int ,int);
void Display2(char ,char ,int );
int a[10] = { 1,2,3,4,5,6,7,8,9,0 };
int b[10] = { 1,3,5,7,9 };
int c[10];
void Difference(int *a1,int *b1,int m1,int n1)
{
q=0;
p=0;
i=0;
for(k=0;k<m1;k++){
flag=1;
for(j=0;j<n1;j++){
if(b1[j]==a1[k]){
flag=1;
q++;
break;
}
else{
flag=0;
}
}
if(flag==0){
c[p]=a1[k];
p++;
}
}
}
void Display2(char ac,char bc,int m1)
{
printf("\nThe Difference Of Two Sets i.e '%c - %c' Is : { ",ac,bc);
r = m1 - q;
for(p=0;p<r;p++){
printf("%2d",c[p]);
}
printf(" }");
}
int main(){
Difference(a,b,m,n);
Display2('A','B',m);
return 0;
}
I can guess, you forgot to initialize your m and n variables with proper values.
Add m = 10; n = 5; before calling Difference and your code will work.
I also suggest you to write more readable code: better naming for variables, use some spaces and avoid global variables.
Edit:
In C++ you can write:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <set>
int main() {
std::set<int> a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::set<int> b = { 1, 3, 5, 7, 9 };
std::set<int> c;
std::set_difference(a.begin(), a.end(), b.begin(), b.end(), std::inserter(c, c.begin()));
for (const auto item : c)
std::cout << item << " ";
return 0;
}
Detail information about std::set_difference can be found here

Passing a 2D array into a function in C [duplicate]

I have a function which I want to take, as a parameter, a 2D array of variable size.
So far I have this:
void myFunction(double** myArray){
myArray[x][y] = 5;
etc...
}
And I have declared an array elsewhere in my code:
double anArray[10][10];
However, calling myFunction(anArray) gives me an error.
I do not want to copy the array when I pass it in. Any changes made in myFunction should alter the state of anArray. If I understand correctly, I only want to pass in as an argument a pointer to a 2D array. The function needs to accept arrays of different sizes also. So for example, [10][10] and [5][5]. How can I do this?
There are three ways to pass a 2D array to a function:
The parameter is a 2D array
int array[10][10];
void passFunc(int a[][10])
{
// ...
}
passFunc(array);
The parameter is an array containing pointers
int *array[10];
for(int i = 0; i < 10; i++)
array[i] = new int[10];
void passFunc(int *a[10]) //Array containing pointers
{
// ...
}
passFunc(array);
The parameter is a pointer to a pointer
int **array;
array = new int *[10];
for(int i = 0; i <10; i++)
array[i] = new int[10];
void passFunc(int **a)
{
// ...
}
passFunc(array);
Fixed Size
1. Pass by reference
template <size_t rows, size_t cols>
void process_2d_array_template(int (&array)[rows][cols])
{
std::cout << __func__ << std::endl;
for (size_t i = 0; i < rows; ++i)
{
std::cout << i << ": ";
for (size_t j = 0; j < cols; ++j)
std::cout << array[i][j] << '\t';
std::cout << std::endl;
}
}
In C++ passing the array by reference without losing the dimension information is probably the safest, since one needn't worry about the caller passing an incorrect dimension (compiler flags when mismatching). However, this isn't possible with dynamic (freestore) arrays; it works for automatic (usually stack-living) arrays only i.e. the dimensionality should be known at compile time.
2. Pass by pointer
void process_2d_array_pointer(int (*array)[5][10])
{
std::cout << __func__ << std::endl;
for (size_t i = 0; i < 5; ++i)
{
std::cout << i << ": ";
for (size_t j = 0; j < 10; ++j)
std::cout << (*array)[i][j] << '\t';
std::cout << std::endl;
}
}
The C equivalent of the previous method is passing the array by pointer. This should not be confused with passing by the array's decayed pointer type (3), which is the common, popular method, albeit less safe than this one but more flexible. Like (1), use this method when all the dimensions of the array is fixed and known at compile-time. Note that when calling the function the array's address should be passed process_2d_array_pointer(&a) and not the address of the first element by decay process_2d_array_pointer(a).
Variable Size
These are inherited from C but are less safe, the compiler has no way of checking, guaranteeing that the caller is passing the required dimensions. The function only banks on what the caller passes in as the dimension(s). These are more flexible than the above ones since arrays of different lengths can be passed to them invariably.
It is to be remembered that there's no such thing as passing an array directly to a function in C [while in C++ they can be passed as a reference (1)]; (2) is passing a pointer to the array and not the array itself. Always passing an array as-is becomes a pointer-copy operation which is facilitated by array's nature of decaying into a pointer.
3. Pass by (value) a pointer to the decayed type
// int array[][10] is just fancy notation for the same thing
void process_2d_array(int (*array)[10], size_t rows)
{
std::cout << __func__ << std::endl;
for (size_t i = 0; i < rows; ++i)
{
std::cout << i << ": ";
for (size_t j = 0; j < 10; ++j)
std::cout << array[i][j] << '\t';
std::cout << std::endl;
}
}
Although int array[][10] is allowed, I'd not recommend it over the above syntax since the above syntax makes it clear that the identifier array is a single pointer to an array of 10 integers, while this syntax looks like it's a 2D array but is the same pointer to an array of 10 integers. Here we know the number of elements in a single row (i.e. the column size, 10 here) but the number of rows is unknown and hence to be passed as an argument. In this case there's some safety since the compiler can flag when a pointer to an array with second dimension not equal to 10 is passed. The first dimension is the varying part and can be omitted. See here for the rationale on why only the first dimension is allowed to be omitted.
4. Pass by pointer to a pointer
// int *array[10] is just fancy notation for the same thing
void process_pointer_2_pointer(int **array, size_t rows, size_t cols)
{
std::cout << __func__ << std::endl;
for (size_t i = 0; i < rows; ++i)
{
std::cout << i << ": ";
for (size_t j = 0; j < cols; ++j)
std::cout << array[i][j] << '\t';
std::cout << std::endl;
}
}
Again there's an alternative syntax of int *array[10] which is the same as int **array. In this syntax the [10] is ignored as it decays into a pointer thereby becoming int **array. Perhaps it is just a cue to the caller that the passed array should have at least 10 columns, even then row count is required. In any case the compiler doesn't flag for any length/size violations (it only checks if the type passed is a pointer to pointer), hence requiring both row and column counts as parameter makes sense here.
Note: (4) is the least safest option since it hardly has any type check and the most inconvenient. One cannot legitimately pass a 2D array to this function; C-FAQ condemns the usual workaround of doing int x[5][10]; process_pointer_2_pointer((int**)&x[0][0], 5, 10); as it may potentially lead to undefined behaviour due to array flattening. The right way of passing an array in this method brings us to the inconvenient part i.e. we need an additional (surrogate) array of pointers with each of its element pointing to the respective row of the actual, to-be-passed array; this surrogate is then passed to the function (see below); all this for getting the same job done as the above methods which are more safer, cleaner and perhaps faster.
Here's a driver program to test the above functions:
#include <iostream>
// copy above functions here
int main()
{
int a[5][10] = { { } };
process_2d_array_template(a);
process_2d_array_pointer(&a); // <-- notice the unusual usage of addressof (&) operator on an array
process_2d_array(a, 5);
// works since a's first dimension decays into a pointer thereby becoming int (*)[10]
int *b[5]; // surrogate
for (size_t i = 0; i < 5; ++i)
{
b[i] = a[i];
}
// another popular way to define b: here the 2D arrays dims may be non-const, runtime var
// int **b = new int*[5];
// for (size_t i = 0; i < 5; ++i) b[i] = new int[10];
process_pointer_2_pointer(b, 5, 10);
// process_2d_array(b, 5);
// doesn't work since b's first dimension decays into a pointer thereby becoming int**
}
A modification to shengy's first suggestion, you can use templates to make the function accept a multi-dimensional array variable (instead of storing an array of pointers that have to be managed and deleted):
template <size_t size_x, size_t size_y>
void func(double (&arr)[size_x][size_y])
{
printf("%p\n", &arr);
}
int main()
{
double a1[10][10];
double a2[5][5];
printf("%p\n%p\n\n", &a1, &a2);
func(a1);
func(a2);
return 0;
}
The print statements are there to show that the arrays are getting passed by reference (by displaying the variables' addresses)
Surprised that no one mentioned this yet, but you can simply template on anything 2D supporting [][] semantics.
template <typename TwoD>
void myFunction(TwoD& myArray){
myArray[x][y] = 5;
etc...
}
// call with
double anArray[10][10];
myFunction(anArray);
It works with any 2D "array-like" datastructure, such as std::vector<std::vector<T>>, or a user defined type to maximize code reuse.
You can create a function template like this:
template<int R, int C>
void myFunction(double (&myArray)[R][C])
{
myArray[x][y] = 5;
etc...
}
Then you have both dimension sizes via R and C. A different function will be created for each array size, so if your function is large and you call it with a variety of different array sizes, this may be costly. You could use it as a wrapper over a function like this though:
void myFunction(double * arr, int R, int C)
{
arr[x * C + y] = 5;
etc...
}
It treats the array as one dimensional, and uses arithmetic to figure out the offsets of the indexes. In this case, you would define the template like this:
template<int C, int R>
void myFunction(double (&myArray)[R][C])
{
myFunction(*myArray, R, C);
}
anArray[10][10] is not a pointer to a pointer, it is a contiguous chunk of memory suitable for storing 100 values of type double, which compiler knows how to address because you specified the dimensions. You need to pass it to a function as an array. You can omit the size of the initial dimension, as follows:
void f(double p[][10]) {
}
However, this will not let you pass arrays with the last dimension other than ten.
The best solution in C++ is to use std::vector<std::vector<double> >: it is nearly as efficient, and significantly more convenient.
Here is a vector of vectors matrix example
#include <iostream>
#include <vector>
using namespace std;
typedef vector< vector<int> > Matrix;
void print(Matrix& m)
{
int M=m.size();
int N=m[0].size();
for(int i=0; i<M; i++) {
for(int j=0; j<N; j++)
cout << m[i][j] << " ";
cout << endl;
}
cout << endl;
}
int main()
{
Matrix m = { {1,2,3,4},
{5,6,7,8},
{9,1,2,3} };
print(m);
//To initialize a 3 x 4 matrix with 0:
Matrix n( 3,vector<int>(4,0));
print(n);
return 0;
}
output:
1 2 3 4
5 6 7 8
9 1 2 3
0 0 0 0
0 0 0 0
0 0 0 0
Single dimensional array decays to a pointer pointer pointing to the first element in the array. While a 2D array decays to a pointer pointing to first row. So, the function prototype should be -
void myFunction(double (*myArray) [10]);
I would prefer std::vector over raw arrays.
We can use several ways to pass a 2D array to a function:
Using single pointer we have to typecast the 2D array.
#include<bits/stdc++.h>
using namespace std;
void func(int *arr, int m, int n)
{
for (int i=0; i<m; i++)
{
for (int j=0; j<n; j++)
{
cout<<*((arr+i*n) + j)<<" ";
}
cout<<endl;
}
}
int main()
{
int m = 3, n = 3;
int arr[m][n] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
func((int *)arr, m, n);
return 0;
}
Using double pointer In this way, we also typecast the 2d array
#include<bits/stdc++.h>
using namespace std;
void func(int **arr, int row, int col)
{
for (int i=0; i<row; i++)
{
for(int j=0 ; j<col; j++)
{
cout<<arr[i][j]<<" ";
}
printf("\n");
}
}
int main()
{
int row, colum;
cin>>row>>colum;
int** arr = new int*[row];
for(int i=0; i<row; i++)
{
arr[i] = new int[colum];
}
for(int i=0; i<row; i++)
{
for(int j=0; j<colum; j++)
{
cin>>arr[i][j];
}
}
func(arr, row, colum);
return 0;
}
You can do something like this...
#include<iostream>
using namespace std;
//for changing values in 2D array
void myFunc(double *a,int rows,int cols){
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
*(a+ i*rows + j)+=10.0;
}
}
}
//for printing 2D array,similar to myFunc
void printArray(double *a,int rows,int cols){
cout<<"Printing your array...\n";
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
cout<<*(a+ i*rows + j)<<" ";
}
cout<<"\n";
}
}
int main(){
//declare and initialize your array
double a[2][2]={{1.5 , 2.5},{3.5 , 4.5}};
//the 1st argument is the address of the first row i.e
//the first 1D array
//the 2nd argument is the no of rows of your array
//the 3rd argument is the no of columns of your array
myFunc(a[0],2,2);
//same way as myFunc
printArray(a[0],2,2);
return 0;
}
Your output will be as follows...
11.5 12.5
13.5 14.5
One important thing for passing multidimensional arrays is:
First array dimension need not be specified.
Second(any any further)dimension must be specified.
1.When only second dimension is available globally (either as a macro or as a global constant)
const int N = 3;
void print(int arr[][N], int m)
{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < N; j++)
printf("%d ", arr[i][j]);
}
int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
print(arr, 3);
return 0;
}
2.Using a single pointer:
In this method,we must typecast the 2D array when passing to function.
void print(int *arr, int m, int n)
{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
printf("%d ", *((arr+i*n) + j));
}
int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int m = 3, n = 3;
// We can also use "print(&arr[0][0], m, n);"
print((int *)arr, m, n);
return 0;
}
#include <iostream>
/**
* Prints out the elements of a 2D array row by row.
*
* #param arr The 2D array whose elements will be printed.
*/
template <typename T, size_t rows, size_t cols>
void Print2DArray(T (&arr)[rows][cols]) {
std::cout << '\n';
for (size_t row = 0; row < rows; row++) {
for (size_t col = 0; col < cols; col++) {
std::cout << arr[row][col] << ' ';
}
std::cout << '\n';
}
}
int main()
{
int i[2][5] = { {0, 1, 2, 3, 4},
{5, 6, 7, 8, 9} };
char c[3][9] = { {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'},
{'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R'},
{'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '&'} };
std::string s[4][4] = { {"Amelia", "Edward", "Israel", "Maddox"},
{"Brandi", "Fabian", "Jordan", "Norman"},
{"Carmen", "George", "Kelvin", "Oliver"},
{"Deanna", "Harvey", "Ludwig", "Philip"} };
Print2DArray(i);
Print2DArray(c);
Print2DArray(s);
std::cout <<'\n';
}
In the case you want to pass a dynamic sized 2-d array to a function, using some pointers could work for you.
void func1(int *arr, int n, int m){
...
int i_j_the_element = arr[i * m + j]; // use the idiom of i * m + j for arr[i][j]
...
}
void func2(){
...
int arr[n][m];
...
func1(&(arr[0][0]), n, m);
}
You can use template facility in C++ to do this. I did something like this :
template<typename T, size_t col>
T process(T a[][col], size_t row) {
...
}
the problem with this approach is that for every value of col which you provide, the a new function definition is instantiated using the template.
so,
int some_mat[3][3], another_mat[4,5];
process(some_mat, 3);
process(another_mat, 4);
instantiates the template twice to produce 2 function definitions (one where col = 3 and one where col = 5).
If you want to pass int a[2][3] to void func(int** pp) you need auxiliary steps as follows.
int a[2][3];
int* p[2] = {a[0],a[1]};
int** pp = p;
func(pp);
As the first [2] can be implicitly specified, it can be simplified further as.
int a[][3];
int* p[] = {a[0],a[1]};
int** pp = p;
func(pp);
You are allowed to omit the leftmost dimension and so you end up with two options:
void f1(double a[][2][3]) { ... }
void f2(double (*a)[2][3]) { ... }
double a[1][2][3];
f1(a); // ok
f2(a); // ok
This is the same with pointers:
// compilation error: cannot convert ‘double (*)[2][3]’ to ‘double***’
// double ***p1 = a;
// compilation error: cannot convert ‘double (*)[2][3]’ to ‘double (**)[3]’
// double (**p2)[3] = a;
double (*p3)[2][3] = a; // ok
// compilation error: array of pointers != pointer to array
// double *p4[2][3] = a;
double (*p5)[3] = a[0]; // ok
double *p6 = a[0][1]; // ok
The decay of an N dimensional array to a pointer to N-1 dimensional array is allowed by C++ standard, since you can lose the leftmost dimension and still being able to correctly access array elements with N-1 dimension information.
Details in here
Though, arrays and pointers are not the same: an array can decay into a pointer, but a pointer doesn't carry state about the size/configuration of the data to which it points.
A char ** is a pointer to a memory block containing character pointers, which themselves point to memory blocks of characters. A char [][] is a single memory block which contains characters. This has an impact on how the compiler translate the code and how the final performance will be.
Source
Despite appearances, the data structure implied by double** is fundamentally incompatible with that of a fixed c-array (double[][]).
The problem is that both are popular (although) misguided ways to deal with arrays in C (or C++).
See https://www.fftw.org/fftw3_doc/Dynamic-Arrays-in-C_002dThe-Wrong-Way.html
If you can't control either part of the code you need a translation layer (called adapt here), as explained here: https://c-faq.com/aryptr/dynmuldimary.html
You need to generate an auxiliary array of pointers, pointing to each row of the c-array.
#include<algorithm>
#include<cassert>
#include<vector>
void myFunction(double** myArray) {
myArray[2][3] = 5;
}
template<std::size_t N, std::size_t M>
auto adapt(double(&Carr2D)[N][M]) {
std::array<double*, N> ret;
std::transform(
std::begin(Carr2D), std::end(Carr2D),
ret.begin(),
[](auto&& row) { return &row[0];}
);
return ret;
}
int main() {
double anArray[10][10];
myFunction( adapt(anArray).data() );
assert(anArray[2][3] == 5);
}
(see working code here: https://godbolt.org/z/7M7KPzbWY)
If it looks like a recipe for disaster is because it is, as I said the two data structures are fundamentally incompatible.
If you can control both ends of the code, these days, you are better off using a modern (or semimodern) array library, like Boost.MultiArray, Boost.uBLAS, Eigen or Multi.
If the arrays are going to be small, you have "tiny" arrays libraries, for example inside Eigen or if you can't afford any dependency you might try simply with std::array<std::array<double, N>, M>.
With Multi, you can simply do this:
#include<multi/array.hpp>
#include<cassert>
namespace multi = boost::multi;
template<class Array2D>
void myFunction(Array2D&& myArray) {
myArray[2][3] = 5;
}
int main() {
multi::array<double, 2> anArray({10, 10});
myFunction(anArray);
assert(anArray[2][3] == 5);
}
(working code: https://godbolt.org/z/7M7KPzbWY)
You could take arrays of an arbitrary number of dimensions by reference and peel off one layer at a time recursively.
Here's an example of a print function for demonstrational purposes:
#include <cstddef>
#include <iostream>
#include <iterator>
#include <string>
#include <type_traits>
template <class T, std::size_t N>
void print(const T (&arr)[N], unsigned indent = 0) {
if constexpr (std::rank_v<T> == 0) {
// inner layer - print the values:
std::cout << std::string(indent, ' ') << '{';
auto it = std::begin(arr);
std::cout << *it;
for (++it; it != std::end(arr); ++it) {
std::cout << ", " << *it;
}
std::cout << '}';
} else {
// still more layers to peel off:
std::cout << std::string(indent, ' ') << "{\n";
auto it = std::begin(arr);
print(*it, indent + 1);
for (++it; it != std::end(arr); ++it) {
std::cout << ",\n";
print(*it, indent + 1);
}
std::cout << '\n' << std::string(indent, ' ') << '}';
}
}
Here's a usage example with a 3 dimensional array:
int main() {
int array[2][3][5]
{
{
{1, 2, 9, -5, 3},
{6, 7, 8, -45, -7},
{11, 12, 13, 14, 25}
},
{
{4, 5, 0, 33, 34},
{8, 9, 99, 54, 44},
{14, 15, 16, 19, 20}
}
};
print(array);
}
... which will produce this output:
{
{
{1, 2, 9, -5, 3},
{6, 7, 8, -45, -7},
{11, 12, 13, 14, 25}
},
{
{4, 5, 0, 33, 34},
{8, 9, 99, 54, 44},
{14, 15, 16, 19, 20}
}
}

copy vector content into an array exercise

I am currently working through C++ Primer 5th edition. In chapter 3, Exercise 3.42, I am asked to "Write a program to copy a vector of int's into an array of int's."
the below code works. However I have a few questions.
1) on line 16,
int arr[5];
initializes an array with 5 elements. How can I alter the array so that it automatically gets/has the same size as the vector ivec?
2) Is there a simpler way to write the program with what the book has taught so far?
//Exercise 3.42
#include "stdafx.h"
#include <iostream>
#include <vector>
using std::vector;
using std::begin;
using std::endl;
using std::cout;
using std::end;
int main(){
vector<int> ivec = { 1, 2, 3, 4, 5 }; //initializes vector ivec.
int arr[5]; //initializes array "arr" with 5 null elements.
int i1 = 0; // initializes an int named i1.
for (vector<int>::iterator i2 = ivec.begin(); i2 != ivec.end(); ++i2){
arr[i1] = *i2; //assigned the elements in ivec into arr.
++i1; // iterates to the next element in arr.
}
for (int r1 : arr){ //range for to print out all elements in arr.
cout << r1 << " ";
}
cout << endl;
system("pause");
return 0;
}
1) You can't in portable C++ with an array : an array length is fixed at compile time. But you could with a vector
2) Certainly, assuming the target array is large enough, use std::copy :
std::copy(std::begin(ivec), std::end(ivec), arr);
Also remove all those using, they are nothing but noise. A little bit a cleaning gives :
#include <iostream>
#include <algorithm>
#include <vector>
int main(){
std::vector<int> ivec = { 1, 2, 3, 4, 5 };
int arr[5];
std::copy(std::begin(ivec), std::end(ivec), arr);
for (auto r1 : arr){
std::cout << r1 << ' ';
}
std::cout << std::endl;
}
You could even reuse std::copy to print the content of the vector :
int main(){
std::vector<int> ivec = { 1, 2, 3, 4, 5 }; //initializes vector ivec.
int arr[5]; //initializes array "arr" with 5 null elements.
std::copy(std::begin(ivec), std::end(ivec), arr);
std::copy(arr, arr + 5, std::ostream_iterator<int>(std::cout, " "));
}
Live demo
Note:
If you want to keep a hand written loop for the copy, a more canonical/c++11 way of doing it is :
auto i1 = std::begin(arr);
auto i2 = std::begin(ivec);
while ( i2 != std::end(ivec)){
*i1++ = *i2++;
}
1) If you need an array with a length that is not known at compile time, you can create the array dynamically on the heap (in real code you should usually rather use std::vector):
int* arr=new int[ivec.size()];
However, this has some other drawbacks. E.g. begin(arr)/end(arr) and thus range for loops don't work anymore and you'll have to manually delete the array at some point (I don't know whether you've already learned about RAII and smart pointers)
2) quantdev has already provided a very good answer for this part

Passing Dynamic Arrays (simple)

Sorry, this is probably a really easy fix but I just can't seem to get it to compile
The assignment requires me to use dynamic memory, and the code has to be written this way.
Basically I can't seem to be able to pass my array to a function.
#include<iostream>
#include<cmath>
using namespace std;
// Comment:
void count(int array[],int length,int& numneg,int& numpos);
// Comment:
void split();
// Comment:
void print_array();
int main(){
int length(0),x(0),numpos(0),numneg(0);
cout << "Enter number of elements: ";
cin >> length;
int *array = new int[length];
cout << "Enter list:" << endl;
cin >> x;
for (int i(0);i<(length-1);i++)
{
array[i] = x;
cin >> x;
}
count(array[length],length,numneg,numpos);
delete [] array;
return 0;
}
void count(int array[],int length,int& numneg, int& numpos)
{
for (int i(0);i<(length-1);i++)
{
if (array[i] < 0)
numneg++;
else
numpos++;
}
}
When passing an array or a pointer to a function, just use the name of the variable.
You call to count needs to be:
count(array,length,numneg,numpos);
By using array[length] you accessing the element of the point at the index of length, which would be an int not an int* not to mention being one element past the size of your buffer.

Resources