Initialization outside the function and initialization inside the function are analyzed in detail

  • 2020-04-02 01:42:07
  • OfStack

On the function of the initialization and the function of the initialization has been separated before not too clear, also do not care too much. This problem finally appeared yesterday, so I decided to have a good look at it. Here are some of the gains of this time, first look at the test code:


#include "stdafx.h"
#include <iostream>
using namespace std;
bool FillStr(char *&szDst, int nSize)
{
 bool bRet = false;
 if (nSize > 0)
 {
  szDst = (char*)malloc(sizeof(char) * nSize);
  memset(szDst, 0, sizeof(char) * nSize);
  strcpy(szDst, "hello, world");
  bRet = true;
 }
 return bRet;
}
bool FillStr(char *szDst)
{
 bool bRet = false;
 if (szDst)
 {
  strcpy(szDst, "hello, 5.1");

  bRet = true;
 }
 return bRet;
}
int _tmain(int argc, _TCHAR* argv[])
{
 char* szWord = NULL;
 //The first kind of
 //FillStr(szWord, 64);
 //The second,
 szWord = (char*)malloc(sizeof(char) * 64);
 memset(szWord, 0, sizeof(char) * 64);
 FillStr(szWord);
 printf("%s/n", szWord);
 if (szWord)
 {
  free(szWord);
  szWord = NULL;
 }
 getchar();
 return 0;
}

1. Function initialization: bool FillStr(char *&szDst, int nSize);

& must not less in the first parameter, this is because we declare only the outside the function pointer, the pointer to the memory of which address we don't know, so & was passed to illustrate is the pointer references, so after initialization in a function pointer to the address that is outside the address pointer.

The second parameter is the number of characters we want to assign.

2. Initialization outside the function: bool FillStr(char *szDst);

The argument of this function can be added with or without ampersand, because it's already initialized when it's passed in, it already has an exact address, if it's passed in without ampersand it's a copy of the original address, if it's added with ampersand it's the same pointer. So in any case they pass in the same address, and the operation on them is the operation on the same block of memory.

Although both of the above methods can achieve the same effect, I think it is better to use the second method, which conforms to the principle of who distributes and who releases.


Related articles: