Trouble with strucutures and pointers

This is a discussion on Trouble with strucutures and pointers within the C Programming forums, part of the General Programming Boards category; Dear all, I have two structures like this: Code: struct Matrix { int r; int c; double * E; }; ...

  1. #1
    Registered User
    Join Date
    Feb 2011
    Posts
    2

    Trouble with strucutures and pointers

    Dear all,

    I have two structures like this:

    Code:
    struct Matrix
    {
      int r;
      int c;
      double * E;     
    };
    
    
    struct Model
    {
        int n;
        int p;
        struct Matrix * pMx;
    };
    And a function which works on a struct matrix; it's prototype is:
    Code:
    double MxGetElement(struct Matrix * p, int iR, int iC)
    This function works well if given a pointer to a Matrix structure.
    I would like to call it through a "Model" pointer, let's call it "pModel".

    I tried
    Code:
     
    x=MxGetElement((struct Matrix *) pModel->pMx, iR, iC);
    x=MxGetElement(&(pModel->pMx), iR, iC);
    etc etc and cannot make it work. Probably simple for you guys. I hope you can help me.

    Many thanks,
    D.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Your first line works. You will have to explain to us why you think it doesn't. (The cast is completely unnecessary, of course.)

  3. #3
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,831
    Code:
    x=MxGetElement(&Model.pMx, iR, iC);
    [corrected it]
    Last edited by nonoob; 02-03-2011 at 12:58 PM.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,636
    This should suffice:
    Code:
    x = MxGetElement(pModel->pMx, iR, iC);
    If it does not, then the problem lies elsewhere.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    Feb 2011
    Posts
    2
    Thanks for quick responses. This is a little odd to me.
    My program works fine when I call it via a Matrix * directly, but it crashes when I go via Model *.
    I have been using C for years for math purposes but never encountered this. How would I find the reason in this case?

    D.

  6. #6
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    You are probably violating an assumption of the MxGetElement function. For instance, MxGetElement might assume that the pointer you pass it actually points to a valid piece of memory, but you pass it a NULL pointer instead.

Popular pages Recent additions subscribe to a feed

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21