简体   繁体   English

指针作为C ++中的参数

[英]Pointers as parameters in C++

I'm new to C++, coming from mostly working with Java and I'm having a problem with a function I'm trying to write. 我是C ++的新手,主要来自于Java的工作,而我尝试编写的函数存在问题。 I'm sure it's something simple, but nonetheless, it's giving me fits, so prepare for a painfully newbie question. 我敢肯定这很简单,但是尽管如此,它还是很合适的,所以请为一个痛苦的新手问题做准备。

I'm trying to write a function as follows: 我正在尝试编写一个函数,如下所示:

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;

}

When I try to run this in XCode (something I'm also new to using), I get a EXE_BAD_ACCESS exception on the printf() portion of foo. 当我尝试在XCode中运行它时(我也很陌生),我在foo的printf()部分得到了EXE_BAD_ACCESS异常。 I'm really not sure what is going on here but I suspect that it has something to do with conflating values, pointers and references, something I don't yet have a strong gasp of how C++ understands them coming from Java. 我真的不确定这里发生了什么,但是我怀疑这与值,指针和引用的合并有关,我对C ++如何理解来自Java的理解还不甚满意。 Does anyone see where I'm slipping up here? 有人看到我在这里溜走了吗?

Thanks. 谢谢。

An u_char would be 1 byte in memory (the name suggests it's just an unsigned char), an int is typically 4 bytes. 一个u_char在内存中将是1个字节(名称表明它只是一个无符号的char),一个int通常是4个字节。 In printf , you tell the runtime to read an int (4 bytes) from the address where counter resides. printf ,您告诉运行时从counter所在的地址读取一个int (4个字节)。 But you only own 1 byte there. 但是您在那里仅拥有1个字节。

EDIT (based on comments down here where poster says it's called actually with the address of an int: foo((u_char*)&count) ): 编辑(基于下面的评论,其中发帖人说实际上是用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.
}

Or even shorter (the wild c-style for which everbody but newbies loves this language): 或更短一些(新手喜欢这种语言的狂野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