今天早上,读《windows程序设计》中的一个名为ENVIRON.C程序中的一段时,对其中一段代码,不死不得其解。上网查了好些资料,终于将其解决。其中就牵扯到了*p++之类的问题。
首先,列出那个程序中的部分代码。
void FillListBox (HWND hwndList)
{
int iLength ;
TCHAR * pVarBlock, * pVarBlock1, * pVarBeg, * pVarEnd, * pVarName ;
pVarBlock = pVarBlock1 = GetEnvironmentStrings () ; // Get pointer to environment block
while (*pVarBlock)
{
if (*pVarBlock != '=') // Skip variable names beginning with '='
{
pVarBeg = pVarBlock ; // Beginning of variable name
while (*pVarBlock++ != '=') ; // Scan until '='
pVarEnd = pVarBlock - 1 ; // Points to '=' sign
iLength = pVarEnd - pVarBeg ; // Length of variable name
// Allocate memory for the variable name and terminating
// zero. Copy the variable name and append a zero.
pVarName = (TCHAR*)calloc (iLength + 1, sizeof (TCHAR)) ;
CopyMemory (pVarName, pVarBeg, iLength * sizeof (TCHAR)) ;
pVarName[iLength] = '\0' ;
// Put the variable name in the list box and free memory.
SendMessage (hwndList, LB_ADDSTRING, 0, (LPARAM) pVarName) ;
free (pVarName) ;
}
while (*pVarBlock++ != '\0') ; // Scan until terminating zero
}
FreeEnvironmentStrings (pVarBlock1) ;
}
while (*pVarBlock++ != '=') ;
上面这行代码就是问题所在。经查阅资料,发现:*p++中,
* 和 ++ 是同一优先级,但是结合方向是
从右向左,关于优先级的详细说明,请参见
运算符优先级列表。也就是说,*pVarBlock++实际上是:
*(pVarBlock++)。具体运算如下:先取*pVarBlock的值之后,再让pVarBlock指向的内存地址自加(加多少视数据类型而定。例如,假设int * pVarBlock,则加4)。
通过这个事情,让我认识到,我对c还是很陌生啊。学无止境,还得继续加油!
至于对这段代码的详细解析,见我另一篇博客。