Home > Software design >  Accessing members of structs using dot or arrow notation
Accessing members of structs using dot or arrow notation

Time:10-02

I was wondering what the pros and cons were or accessing members of a struct using the notation mystruct.element1 rather than mystruct->element1.

Or rather is it better or worse to define structs as pointers or not, i.e.

structtype * mystruct; or structtype mystruct; 

In my code, I would be wanting to pass various structs as inputs to some functions and currently I'm passing them as references as shown below:

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

where the struct would be defined as usual (I think)

struct structtype{
    double element0;
};
structtype mystruct;

CodePudding user response:

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);
  • Related