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

  • Thread starter Thread starter eswarm21
  • Start date Start date
  • Tags Tags
    2d Array C++
AI Thread Summary
The discussion revolves around a user's query about passing values to a subroutine in C and returning results to the main program. The user is trying to implement a function that calculates a value based on a 2D array. Key points include the need for proper array handling in C, with suggestions to either make the array global or pass it as a parameter to the function. There is clarification that when using global variables, the updated values will be accessible in the subroutine, and the returned value can be used in the main program. The conversation also touches on the differences between C and C++ programming, emphasizing that while the syntax may differ, C++ offers more advanced data structures and features, which can lead to different solutions for similar problems. The importance of understanding these differences is highlighted, particularly in the context of numerical programming and data handling. Overall, the thread serves as a practical guide for handling arrays and functions in C, while also addressing broader programming concepts relevant to both C and C++.
eswarm21
Messages
8
Reaction score
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
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.
 
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[][]).
 
#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..?
 
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.
 
eswarm21, why do you add "C++" to your headline when you want to deploy "C" only?
 
Last edited:
thanks to all...

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

nice how to do "C++" in my head line?
 
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.
 
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:
Back
Top