How to Pass a 2D Array in C and C++ for Numerical Computing

In summary: For example, one can implement the functionality of a two-dimensional array by using a "vector of vectors." A vector is a dynamically allocated array, so it can grow and shrink as needed. You can also use a deque, which is like a vector but allows insertion and deletion at both ends with the same efficiency as at the middle.Another advantage of using a vector (or deque) of vectors is that you don't have to enforce a rectangular shape. Each row can have a different number of columns if you want. You can also add or remove rows with minimal overhead.Here is an example of a vector of vectors:#include <iostream>#include <vector>#include <iomanip>int main(){ std::vector<std::vector<double
  • #1
eswarm21
8
0
Hi I have this small doubt. i am not good in C . i like to bring i,j,pi values to subroutine and bring back Asi to main program. how to write ! Plz help..

#include <stdlib.h>
#include <math.h>
double A_operate(int i,int j)

void main()
{
double Ai, pi[10][10],r[10][10];
int i,j,n,m;
n=6;
m=6;

for (i=2;i<n;i++)
{
for (j=2;j<m;j++)
{
pi[j]=pow((i+j),2)
Ai=A_operate(i,j);
r[j]=Ai;
}
}
}// main ends

double A_operate(int i,int j)
{
double Asi;
Asi=20*pi[j];
return (Asi);
}
 
Last edited:
Technology news on Phys.org
  • #2
lots wrong with that code. a 2d array is an array of pointers T** where T is an arbitrary type.
Read more about writing C.
 
  • #3
You could move pi[][] outside of main and make it a global, or you can pass it as a parameter: A_operate(int i, int j, double pi[][]).
 
  • #4
#include <stdlib.h>
#include <math.h>
double A_operate(int i,int j, double pi[][])
double pi[10][10],r[10][10];

void main()
{
double Ai;
int i,j,n,m;
n=6;
m=6;

for (i=2;i<n;i++)
{
for (j=2;j<m;j++)
{
pi[j]=pow((i+j),2)
Ai=A_operate(i,j, pi[][]);
r[j]=Ai;
}
}
}// main ends

double A_operate(int i,int j, double pi [][])
{
double Asi;
Asi=20*pi[j];
return (Asi);
}
Is it ok ?... i think still some problem is there...

if i make global like this ... will it use updated pi in subroutine ?? will it bring Asi to main program.?...Can anyone write the same program as an expert would..?
 
  • #5
eswarm21 said:
if i make global like this ... will it use updated pi in subroutine?
Yes, but now that you made it global, you don't need to pass it as a parameter.

eswarm21 said:
will it bring Asi to main program?
It will return the value of Asi, which is good enough.
 
  • #6
eswarm21, why do you add "C++" to your headline when you want to deploy "C" only?
 
Last edited:
  • #7
thanks to all...

why do you add "C++" to your headline?

nice how to do "C++" in my head line?
 
  • #8
It's somewhat annoying if people needlessly include "C++" when raising questions about plain "C" coding.

A quality C++ solution often would look entirely different than any solution possible with C.
 
  • #9
Note, arrays are passed to functions by reference (by their address). You have to specify the size of all but the first dimension so the function knows how to access the array. Example for a 2d array. The hex printf prints out the address of the matrix so you can see that it is the same.

Code:
#include <stdio.h>
#define NCOL 8
#define NROW 4

int test(int [][NCOL]);

int main()
{
unsigned int i, j;
int a2d[NROW][NCOL];

    for(j = 0; j < NROW; j ++){
        for(i = 0; i < NCOL; i++){
            a2d[j][i] = j*10 + i;
            printf("%2d ", a2d[j][i]);
        }
        printf("\n");
    }
    printf("%08x\n", &a2d[0][0]);
    test(a2d);
    return(0);  
}

int test(int x2d[][NCOL])
{
    printf("%08x\n", &x2d[0][0]);
    return(0);
}
 
Last edited:
  • #10
oohhh sorry about title .. actually i am compiling in C++ compiler. But I wrote my code in C .
I am using these codes for very simple purposes. OK ... i didnt understand "solution differs between C and C++"... it surprises me ...
 
  • #11
eswarm21 said:
I didnt understand "solution differs between C and C++".
It doesn't have to differ, but it can. For example, you could use cout to output data instead of printf.
 
Last edited:
  • #12
yes fine ... rcgldr ...But Solkar says that "C++ solution differs from solution possible with C". I think only the syntax is different . Isnt it ??...
 
  • #13
eswarm21 said:
yes fine ... rcgldr ... but Solkar says that "C++ solution differs from solution possible with C". I think only the syntax is different. Isnt it ?

My previous example in c++ using cout:

Code:
#include <iostream>
#include <iomanip>
using namespace std;

#define NCOL 8
#define NROW 4

int test(int [][NCOL]);

int main()
{
unsigned int i, j;
int a2d[NROW][NCOL];

    for(j = 0; j < NROW; j ++){
        for(i = 0; i < NCOL; i++){
            a2d[j][i] = j*10 + i;
            cout << std::setw(2) << a2d[j][i] << ' ';
        }
        cout << endl;
    }
    cout << std::setw(8) << std::hex << &a2d[0][0] << endl;
    test(a2d);
    return(0);  
}

int test(int x2d[][NCOL])
{
    cout << std::setw(8) << std::hex << &x2d[0][0] << endl;
    return(0);
}
 
Last edited:
  • #14
eswarm21 said:
But Solkar says that "C++ solution differs from solution possible with C". I think only the syntax is different . Isnt it ??...

C++ is not limited to arrays for storing sets of data. It has a rich variety of "container" data types with various performance characteristics.

For example, one can implement the functionality of a two-dimensional array by using a "vector of vectors," as in my example in this earlier thread:

https://www.physicsforums.com/showthread.php?t=509358
 
  • #15
eswarm21 said:
But Solkar says that "C++ solution differs from solution possible with C".
In fact I wrote
Solkar said:
A quality C++ solution often would look entirely different than any solution possible with C.
. (emphasis added)

And that is not restricted to
rcgldr said:
you could use cout to output data instead of printf.
stream usage, although having a clear interface for stream iteration is an asset, e.g.
Code:
/* given */ typedef double real;
// [...]
for (std::size_t i = 0; i < M; ++i) {
    std::copy(R[i], R[i]+N, std::ostream_iterator<real>(std::cout, "\t"));
    std::cout << std::endl;
}
saves some overhead of
Code:
for (int i = 0; i < M; ++i) {
    for (int j = 0; j < N; ++j) {
        printf("%f\t", R[i][j]);
    }
    printf("\n");
}
, but that is not such a big deal as often claimed.

The important aspect of C++ for numerics is this
jtbell said:
C++ is not limited to arrays for storing sets of data. It has a rich variety of "container" data types with various performance characteristics.
along with iterators, functors, algorithms, operator overloading and encapsulation, and generic polymorphism in general.

Consider e.g. this
Code:
template <
    std::size_t M,
    std::size_t N,
    typename T
> class Matrix  {
    std::valarray<T> _data;
    
  public:
    Matrix() : _data(T(0), M*N) {};
    
    inline T* operator[] (std::size_t i) {
        return &_data[i*N];
    }
    
    inline Matrix& operator*= (const T& r) {
        _data *= r;
        return *this;
    }
    
    inline T* begin() {
        return &_data[0];
    }
    
    inline T* end() {
        return &_data[0] + _data.size();
    }
};

This is neither intended to be "the" best matrix class (there is nothing like "the best" at all), nor sth. for production usage (let alone supposed to be complete in any means¹); it's just to meet the requirements of the OP in a flexible way by means of C++.

At its heart there's this one
Code:
std::valarray<T> _data;
hidden from the public; here just² to be understood as a plain chunk storage of numerical values along with some handy overloaded operators for bulk ops like this
Code:
_data *= r;

Furthermore, this accessor
Code:
inline T* operator[] (std::size_t i) {
    return &_data[i*N];
}
is implemented C/C++-style, that is, row-major ordering.

For e.g. OpenGL or Fortran interop, column-major ordering would be better, so if that requirement would arise in the future, one could simply replace "i*N" with "i*M" and keep the rest intact.

For serious programming, one would not rely on "replacing" sth in much tested code, but would design the template accordingly from the beginning, but that's not our point here.

Another feature is this one
Code:
inline T* begin() {
    return &_data[0];
}
    
inline T* end() {
    return &_data[0] + _data.size();
}

which offers two convenience STL-style iterators for usage with STL-algorithms and functors; eg the initial fill could be carried out by sth like
Code:
std::generate(P.begin(), P.end(), init);
where "init" is an instance of a custom "functor", that is a class with a custom "( )" operator.

---

That should be enough to demonstrate that there's more about C++ than just a fancier output syntax.

Regards, Solkar



¹To see a really sophisticated matrix implementation with C++ pls attend Boost uBLAS
²the concept behind std:valarray is in fact much more elaborate, but that's not our topic here
 
Last edited:
  • #16
Solkar said:
It's somewhat annoying if people needlessly include "C++" when raising questions about plain "C" coding.

i would agree that it's a C question. even with C++, when you drill down to the "leaf" methods (i don't know what you call them, but in C we might call functions that don't call other functions a "leaf", you cannot have indirect referrals forever if you want to actually get something done) the code is C.

A quality C++ solution often would look entirely different than any solution possible with C.

i would be careful with that remark. I've seen some really crappy C++ "solutions". C++ is an OOP, but it's an ugly and inconcise OOP. C++ is not Smalltalk.
 
  • #17
rbj said:
I've seen some really crappy C++ "solutions". C++ is an OOP, but it's an ugly and inconcise OOP. C++ is not Smalltalk.

Well... "OOP" in a strict sense and HPC numerics don`t go well together, e.g. "late binding" and "vectorization" bite each other.

STL/Boost-like generic polymorphism is a different topic.

Personally speaking I do
- system programming with plain C99
- complicated maths with Fortran
- and all the rest needed to be compiled (esp application of graph theory) with C++,

and I tend to keep this apart module- or even process-wise.

Regards, Solkar
 
Last edited:

Related to How to Pass a 2D Array in C and C++ for Numerical Computing

1. How do you declare a 2D array in C and C++?

In both C and C++, a 2D array can be declared by specifying the number of rows and columns in square brackets after the array name. For example:
int arr[3][4];
This would create a 2D array with 3 rows and 4 columns.

2. How do you pass a 2D array as a function parameter in C and C++?

To pass a 2D array as a function parameter in C and C++, you can either pass the array as a pointer to its first element, along with the number of rows and columns, or you can pass it as a pointer to an array of pointers. In both cases, the function prototype should include the size of the array as a parameter.

3. What is the difference between passing a 2D array and a 2D pointer in C and C++?

A 2D array and a 2D pointer are not the same thing in C and C++. A 2D array is a block of memory with a fixed size, while a 2D pointer is a pointer to an array of pointers, which can be dynamically allocated. When passing a 2D array, the function receives a copy of the array, while when passing a 2D pointer, the function receives a copy of the pointer, which means it can modify the original array.

4. Can a 2D array have different data types in C and C++?

No, a 2D array must have the same data type for all of its elements in C and C++. This is because the compiler needs to know how much memory to allocate for each element in the array.

5. How do you access a specific element in a 2D array in C and C++?

To access a specific element in a 2D array in C and C++, you can use the array indices, just like with a 1D array. For example:
int arr[3][4];
arr[0][2] = 5;
This would set the element at row 0, column 2 to the value 5.

Similar threads

  • Programming and Computer Science
Replies
3
Views
1K
  • Programming and Computer Science
Replies
25
Views
2K
  • Programming and Computer Science
Replies
12
Views
1K
  • Programming and Computer Science
Replies
1
Views
981
  • Programming and Computer Science
Replies
4
Views
693
  • Programming and Computer Science
Replies
20
Views
1K
  • Programming and Computer Science
Replies
6
Views
8K
  • Engineering and Comp Sci Homework Help
Replies
17
Views
1K
  • Programming and Computer Science
Replies
23
Views
1K
  • Programming and Computer Science
Replies
4
Views
3K
Back
Top