Z
Z
ZhGhost2018-03-26 00:30:22
C++ / C#
ZhGhost, 2018-03-26 00:30:22

How are references and pointers used in C++?

Once again, hello everyone! Why, in this example, a reference (&sync) is passed to the function, and not just the name of the variable (sync), as in C#, for example.

stOnFootData sync;
memset( &sync, 0, sizeof( stOnFootData ) );

Now about pointers
In the previous question, I asked about *, now I'm generally wondering what the assignment operation is for? After all, a pointer stores the address of a variable. Why can't you just use it?
int *p = 0x1010101;
*p = 1;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Moseychuk, 2018-03-26
@fshp

In the first part of the question, you are not passing a reference, but a pointer.
& in this case is the operation of taking the address of a variable. If you look at the documentation, you will see that memset takes a pointer.
The second part is not clear. You ask why the operation is needed and immediately show an example of its use.

R
res2001, 2018-03-26
@res2001

A pointer is the same variable as all the others, i.e. a memory area to store an integer value. To use it, you must first initialize it with the correct value, otherwise you will get an error / warning at the compilation stage.
Those. to use *p, p must contain a valid value, so this operator is preceded by an assignment. In principle, your example will compile, but most likely it will cause the program to crash, because The address 0x1010101 is taken from the ceiling and most likely points to an unallocated memory area. It may not cause a fall, then how lucky.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question