user1812302
user1812302

Reputation: 21

Passing an int to a function that expects char*

I want to pass an int to a function that expects a char *.

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..)

int numLine;
swapEndian(numLine, sizeof(int));

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

Upvotes: 2

Views: 1599

Answers (4)

In addition to other answers, assuming the swapEndian does what it name suggests, I believe it is wrongly declared. I suggest to declare it (if you can)

   void swapEndian(void *pElement, size_t uNumBytes);

Upvotes: 0

jheriko
jheriko

Reputation: 3113

The char* cast already suggested will work

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

...however if you can change swapEndian to take a void* it would be better since it avoids needing the cast (this is basically what void pointers are meant for) and also avoids any potential problems or potential future problems to do with the casting operation itself...

Upvotes: 3

Benj
Benj

Reputation: 32398

It sounds as though you just want:

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

Upvotes: 3

md5
md5

Reputation: 23709

If swapEndian works with every pointers to object, then you can pass your pointer, because, according to the strict aliasing rule, a pointer to a character type can be dereference regardless to the type of the pointed object. You just need a typecast.

swapEndian((char *)&numLine, sizeof numLine);

C11 (n1570), § 6.5 Expressions

An object shall have its stored value accessed only by an lvalue expression that has one of the following types:

— a type compatible with the effective type of the object,

— a qualified version of a type compatible with the effective type of the object,

— a type that is the signed or unsigned type corresponding to the effective type of the object,

— a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,

— an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or

— a character type.

Upvotes: 0

Related Questions