How to return a value from a pointer in C
I have the following code and I would like to return the value of 'out' and print it to a file. How do I return the value of 'out' instead of the location. Also, how do I call the function uint32_pack from the main function? Thank you for your help.
#if HAVE_PROTOBUF_C_CONFIG_H
#include "protobuf-c-config.h"
#endif
#include <stdio.h> /* for occasional printf()s */
#include <stdlib.h> /* for abort(), malloc() etc */
#include <string.h> /* for strlen(), memcpy(), memmove() */
#if HAVE_ALLOCA_H
#include <alloca.h>
#elif HAVE_MALLOC_H
#include <malloc.h>
#endif
#include "protobuf-c.h"
int main(void){
uint32_t hexvalue = 0x20;
int gnuvalue;
uint8_t fake_out;
FILE *fp;
fp = fopen("binarydata.txt","w");
gn开发者_Python百科uvalue = uint32_pack (hexvalue, fake_out);
fprintf(fp,"%x",gnuvalue);
fclose(fp);
}
/* === pack() === */
/* Pack an unsigned 32-bit integer in base-128 encoding, and return the number of bytes needed:
this will be 5 or less. */
static inline size_t
uint32_pack (uint32_t value, uint8_t *out)
{
unsigned rv = 0;
if (value >= 0x80)
{
out[rv++] = value | 0x80;
value >>= 7;
if (value >= 0x80)
{
out[rv++] = value | 0x80;
value >>= 7;
if (value >= 0x80)
{
out[rv++] = value | 0x80;
value >>= 7;
if (value >= 0x80)
{
out[rv++] = value | 0x80;
value >>= 7;
}
}
}
/* assert: value<128 */
out[rv++] = value;
return &out;
}
}
You want to dereference the pointer using the *
unary operator, like so:
return *out;
Doing this, it'll return the value stored at the location pointed to by out
.
There something odd in your code here
uint8_t fake_out;
gnuvalue = uint32_pack (hexvalue, fake_out);
while the prototype for uint32_pack needs uint8_t *
, so it should be &fake_out
. And then to return it, you need just to dereference the pointer to modify fake_out,something like *out = value;
.
If you need to return two values (gnuvalue and fake_out), this is how you can.
Another option could be to return a pointer to a struct malloc-ed in the function (then you need to free it soon or later), and the struct holds both "gnuvalue" and "fake_out".
You should return *out
. And update the comment to reflect this. In practice it seems like out
should fit in a size_t
(i.e. sizeof size_t
will be large enough) but it is hack-ish to assume it.
On calling from main, the current way won't work because fake_out
is an uint8_t
, not an uint8_t*
. Of course &fakeout
will crash so don't do that, you have to allocate a large enough array of uint8_t
.
精彩评论