Passing an int to a function that expects char*

Nov 9, 2012 at 1:23pm
Hi,
I want to pass an int to a function that expects a char *. Programming in Linux, so can't use itoa.
The function header looks like this:

void swapEndian(char *pElement, unsigned int uNumBytes)

and calling the function with an int (I know, this won't work..)
1
2
int numLine;
swapEndian(numLine, sizeof(int));


So what must I do to numline to pass it to this function?



Last edited on Nov 9, 2012 at 1:23pm
Nov 9, 2012 at 1:28pm
Try the following

swapEndian( reinterpret_cast<char *>( &numLine ), sizeof(int));
Nov 9, 2012 at 1:40pm
reinterpret_cast is C++. Maybe this was not the correct forum to ask the question as I'm programming C, but if anyone can give me a C solution, will be appreciated.
Nov 9, 2012 at 1:55pm
In C there's only one cast expression, so that's what you'd use:

1
2
    int numLine;
    swapEndian((char*)&numLine, sizeof numLine);


Note that, since you're on Linux, you can deal with the endian-ness issues using the POSIX functions htonl and ntohl: http://pubs.opengroup.org/onlinepubs/9699919799/functions/htonl.html instead of writing your own.
Nov 9, 2012 at 2:57pm
If your function requires a character string, then you could use sprintf() to make the int into a string.
Topic archived. No new replies allowed.