TomSawyer TomSawyer - 2 months ago 7
C++ Question

Benefits of using pointer in this example?

I'm beginning with C++ , and really don't see the advantage of pointer.
I see many people say pointer helps to save memory or good in memory management.

Like bellow examples, they return the same result, what different if i use pointer in this case?

Without pointer

typedef struct
{
int book_id;
} Books;

void printbookinf( Books book );

int main( )
{
Books bno1;
Books bno2;

bno1.book_id = 1225;
bno2.book_id = 3214;

printbookinf( bno1 );
printbookinf( bno2 );

return 0;
}
void printbookinf( Books book )
{
printf("abc %d",book.book_id);
}


with pointer

typedef struct
{
int book_id;
} Books;

void printbookinf( Books *book );

int main( )
{
Books bno1;
Books bno2;

bno1.book_id = 1225;
bno2.book_id = 3214;

printbookinf( &bno1 );
printbookinf( &bno2 );

return 0;
}
void printbookinf( Books *book )
{
printf("abc %d",book->book_id);
}


or this

typedef struct
{
int book_id;
} Books;

void printbookinf( Books *book );

int main( )
{
Books *bno1;
Books *bno2;

bno1->book_id = 1225;
bno2->book_id = 3214;

printbookinf( bno1 );
printbookinf( bno2 );

return 0;
}
void printbookinf( Books *book )
{
printf("abc %d",book->book_id);
}

Answer

I see many people say pointer helps to save memory or good in memory management.

That's not what pointers are for in general. In your example the pointers would have helped you save memory and transfer of data, had the struct been larger than a pointer.

The first example copies the struct when passing parameter. This means two things:

  • The whole structure, even a large one, would be copied, and the copy would be passed to the function
  • Any modifications inside the function would be invisible to the caller.

The second example passes a pointer, so

  • Only the pointer gets copied, and
  • Changes, if any, are performed on the original parameter passed to the function.

Your third example has undefined behavior, because pointers that you pass are unassigned.

Note: Your question does not ask about references, but there is a construct that is closely related to pointers that lets you save space on argument copying, and it lets the function make modifications to the original value. All that happens while keeping the dot . syntax for accessing members, as if it were a struct, not a pointer.

Comments