繁体   English   中英

指针作为C ++中的参数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM