下面我有一些代碼可以做同樣的事情並給出相同的輸出。在第一個中,我使用了指針參數傳遞指針來消除使用全局的ans
。在第二個,我發ans
全局與指針處理,以指針時消除*
的附加用途:指針或全局變量的指針?
實施例1:
// pointer to pointer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
unsigned char serial[] = {
0x1,0x2,0x3,0x4
};
void checkSerial(unsigned char* buf, unsigned char ** ans)
{
int i;
unsigned char *part;
part = 0;
i=2;
part = &buf[i];
*ans = (unsigned char*)malloc(2);
memset(*ans,0,2);
memcpy(*ans,part,2);
printf("0x%x\n",**ans);
++(*ans);
printf("0x%x\n",**ans);
}
int main(void)
{
unsigned char *ans, *buf;
while(1)
{
buf = malloc(4);
memset(buf,0,4);
memcpy(buf, serial, sizeof(serial));
checkSerial(buf, &ans);
--ans;
printf("the value is 0x%x\n", *ans);
free(buf);
free(ans);
sleep(3);
}
return 0;
}
實施例2:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
unsigned char serial[] = {
0x1,0x2,0x3,0x4
};
unsigned char ans[2];
void checkSerial(unsigned char* buf)
{
int i;
unsigned char *part;
part = 0;
i=2;
part = &buf[i];
int j;
for(j=0;j<2;j++)
{
ans[j] = part[j];
}
printf("0x%x\n",*ans);
++(*ans);
printf("0x%x\n",*ans);
}
int main(void)
{
unsigned char *buf;
while(1)
{
buf = malloc(4);
memset(buf,0,4);
memcpy(buf, serial, sizeof(serial));
checkSerial(buf);
printf("the value is 0x%x\n", *ans);
free(buf);
sleep(3);
}
return 0;
}
哪種技術是首選C?
我個人也不會使用。你已經在while循環中分配了buf來傳入序列號,所以id也在while循環中分配了ans,並將其傳遞到checkSerial中以填充。此外,你的全局ans不夠大,不足以適應它的答案只有1個字節不是2. – Dampsquid
你確定要用'--ans;'......減少'ans'指針嗎?可能你的意思是減少一個值得考慮的價值,那就是' - * ans;'...? – CiaPan
儘管不推薦使用全局變量,但如果變量的分配距離很遠,則創建指向指針的指針會在彙編級別創建兩個間接級別。如果這些變量未緩存在單個緩存中,則這可能會導致性能損失線導致處理器停頓並計算第二個變量的地址並將該變量/高速緩存線置於其上進行操作。 – Recker