2

我是 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 有强烈的喘息。有人看到我在这里滑倒了吗?

谢谢。

4

2 回答 2

4

Anu_char将是内存中的 1 个字节(顾名思义,它只是一个无符号字符),anint通常是 4 个字节。在printf中,您告诉运行时从所驻留int的地址读取一个(4 个字节) 。counter但是你在那里只有 1 个字节。

于 2013-06-13T23:14:54.203 回答
0

编辑(根据这里的评论,海报说它实际上是用 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)++);
}
于 2013-06-13T23:19:26.857 回答