Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Passing 2D array in C and C++

  1. Apr 19, 2013 #1
    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: Apr 20, 2013
  2. jcsd
  3. Apr 20, 2013 #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.
     
  4. Apr 20, 2013 #3

    rcgldr

    User Avatar
    Homework Helper

    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[][]).
     
  5. Apr 20, 2013 #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 any one write the same program as an expert would..???
     
  6. Apr 20, 2013 #5

    rcgldr

    User Avatar
    Homework Helper

    Yes, but now that you made it global, you don't need to pass it as a parameter.

    It will return the value of Asi, which is good enough.
     
  7. Apr 20, 2013 #6
    eswarm21, why do you add "C++" to your headline when you want to deploy "C" only?
     
    Last edited: Apr 20, 2013
  8. Apr 20, 2013 #7
    thanks to all....

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

    nice how to do "C++" in my head line?
     
  9. Apr 20, 2013 #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.
     
  10. Apr 20, 2013 #9

    rcgldr

    User Avatar
    Homework Helper

    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 (Text):

    #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: Apr 20, 2013
  11. Apr 20, 2013 #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 .....
     
  12. Apr 20, 2013 #11

    rcgldr

    User Avatar
    Homework Helper

    It doesn't have to differ, but it can. For example, you could use cout to output data instead of printf.
     
    Last edited: Apr 20, 2013
  13. Apr 20, 2013 #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 ??....
     
  14. Apr 20, 2013 #13

    rcgldr

    User Avatar
    Homework Helper

    My previous example in c++ using cout:

    Code (Text):

    #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: Apr 20, 2013
  15. Apr 20, 2013 #14

    jtbell

    User Avatar

    Staff: Mentor

    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
     
  16. Apr 20, 2013 #15
    In fact I wrote
    . (emphasis added)

    And that is not restricted to
    stream usage, although having a clear interface for stream iteration is an asset, e.g.
    Code (Text):

    /* 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 (Text):
    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
    along with iterators, functors, algorithms, operator overloading and encapsulation, and generic polymorphism in general.

    Consider e.g. this
    Code (Text):
    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 (Text):
    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 (Text):
    _data *= r;
    Furthermore, this accessor
    Code (Text):

    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 (Text):
    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 (Text):
    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: Apr 20, 2013
  17. Apr 20, 2013 #16

    rbj

    User Avatar

    i would agree that it's a C question. even with C++, when you drill down to the "leaf" methods (i dunno 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.

    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.
     
  18. Apr 20, 2013 #17
    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: Apr 20, 2013
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Passing 2D array in C and C++
Loading...