Hello! Please tell me, recently started learning C ++, confusing with pointers. Suppose there is such a function.

void abcd(TCHAR *app){ TCHAR tBufApp[256 + 1]; wsprintf(tBufApp, _T("%s"), app); } 

Question 1) Do I need to write & before the app in fs and wsprintf ? When do you need to write it (ampersand)?

Question 2) Do I call the function correctly?

 TCHAR app[256+1]; abcd(app); 

Thank!

  • do not use TCHAR, use char or wchar_t depending on what you need. - Abyx
  • And for what reason? How can this affect? - RemezW
  • In short, TCHAR is a data type that either char or wchar_t (depending on the project settings) and its use turns porting code into a hell of a headache. more about TCHAR here: habrahabr.ru/post/164193 . - goldstar_labs

2 answers 2

The & operator - getting the address of an object, you can assign the received address to a pointer variable:

 int foo = 1; int* ptr = &foo; 

Operator * - pointer dereference, i.e. getting the value of a variable at:

 int bar = *ptr; 

In addition, c ++ allows implicit conversion of a link to an array into a pointer to its first element, i.e. This code is correct:

 int array[256]; int* p = array; 
  • Understood thanks! So, in my case, everything is correct? Or, when you call, you need to do something like this abcd (& app); ? - RemezW

Briefly - 1) no 2) yes

& is an address retrieval statement. &app is the address of the argument passed to the function, i.e. the address of the memory cell in the stack where it will be put. You also need to pass the address of the line from which the information will be taken to sprintf . This address is contained in the app variable itself, so you must pass in its value, not its address.

Globally - when you need to write & - to answer unambiguously and simply will not work, if not limited to some particulars. Simplified like this - you just need to understand what is expected of you - some value, or indicate where this value is located.

On the second question - when passing an array to a function, its name is replaced with the address of the first element, so that you are passing everything correctly.