[英]Pointers as parameters in C++
我是C ++的新手,主要來自於Java的工作,而我嘗試編寫的函數存在問題。 我敢肯定這很簡單,但是盡管如此,它還是很合適的,所以請為一個痛苦的新手問題做准備。
我正在嘗試編寫一個函數,如下所示:
void foo(u_char *ct){
/* ct is a counter variable,
it must be written this way due to the library
I need to use keeping it as an arbitrary user argument*/
/*here I would just like to convert the u_char to an int,
print and increment it for each call to foo,
the code sample I'm working from attempts to do it more or less as follows:*/
int *counter = (int *) ct;
printf("Count: %d\n", *counter);
*counter++;
return;
}
當我嘗試在XCode中運行它時(我也很陌生),我在foo的printf()部分得到了EXE_BAD_ACCESS異常。 我真的不確定這里發生了什么,但是我懷疑這與值,指針和引用的合並有關,我對C ++如何理解來自Java的理解還不甚滿意。 有人看到我在這里溜走了嗎?
謝謝。
一個u_char
在內存中將是1個字節(名稱表明它只是一個無符號的char),一個int
通常是4個字節。 在printf
,您告訴運行時從counter
所在的地址讀取一個int
(4個字節)。 但是您在那里僅擁有1個字節。
編輯(基於下面的評論,其中發帖人說實際上是用int的地址調用的: foo((u_char*)&count)
):
void foo(u_char *ct)
{
int *pcounter = (int *)ct; // change pointer back to an int *
printf("Count: %d\n", *pcounter);
(*pcounter)++; // <<-- brackets here because of operator precedence.
}
或更短一些(新手喜歡這種語言的狂野C風格):
void foo(u_char *ct)
{
printf("Count: %d\n", (*(int *)ct)++);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.