c++pointersstructreferencemember

Accessing members of structs using dot or arrow notation


What are the pros and cons of accessing members of a struct using the (dot) notation mystruct.element1 versus the (arrow) notation mystruct->element1?

Is it better to define structs as pointers or not?

i.e. structtype * mystruct; or as structtype mystruct;

In my code, I want to pass structs as inputs to functions. Currently I'm passing them as references:

void myfunc(structtype &mystruct, double a[]) 
{
     a[0] = mystruct.element0;
}

Where (I think) the struct would be defined as:

struct structtype{
    double element0;
};
structtype mystruct;

Solution

  • it depends on the case , creating a pointer of type structtype will come good in some cases where the memory space is critical.

    look as for example in the next code:

    #include <iostream>
    using namespace std;
    
    struct structtype {
        double element0;
        int element1;
        int element2;
    };
    
    structtype mystruct;
    
    void func(structtype &s)
    {
        cout << "size of reference pointer : "  << sizeof(&s);
    }
    
    int main() {
        cout <<"size of object : " << sizeof(mystruct) << endl;
        func(mystruct);
        return 0;
    }
    

    and this is the output :

    size of object : 16
    size of reference pointer : 4
    

    notice the size occupied by the pointer is only 4 bytes not 16 bytes. so pointers come in handy when you want to save space as instead of creating multiple objects where each object is of size 16 bytes which will consume the memory , you can create only one object and make any function call just refer to the address of that object so you can save some memory.

    also in other cases , you will need your object not to be destructed like the following code:

    #include <stdio.h>
    #include <stdlib.h>
    
    
    typedef struct structtype {
        double element0;
        int element1;
        int element2;
    }structtype;
    
    structtype* func()
    {
        structtype s1;
        s1.element1 = 1;
        return &s1;
    }
    
    int main() {
        structtype *sRet = func();
        structtype s2 = {1546545, 5, 10};
        printf("element1 : %d", sRet->element1);
        return 0;
    }
    

    the above code is undefined behavior and will through some strange output as structtype s1; is declared as object not pointer to object in heap so at the end of the function called func , it will be destructed and not be in the stack , while in the case of pointers , you can create a pointer to object that's in heap that can't be destroyed unless you specify that explicitly , and so the pointers come in handy in that point also. you can create a pointer to object that's in heap in c++ like this:

    structtype *s1 = new structtype;
    

    and to free that memory , you have to type in c++ :

    delete(s1);