Passing a constant integer when a function expects a pointer

What is the best / most canonical way to pass in a constant integer value to a function waiting for a pointer?

For example, the function write

write (int filedes, const void *buffer, size_t size);

Say I just want to write one byte (a 1), I would think about this:

write (fd, 1, 1);

but I obviously get a warning

warning: passing argument 2 of 'write' makes pointer from integer without a cast

I know what I can do

int i = 1;
write (fd, &i, 1);

but is it necessary? What is the best way to do this without having to declare / initialize a new variable?

+5
source share
7 answers

C89/90 , . C , lvalues. Lvalue - , . , , -, . , , . C lvalues, . , , . C89/90 : . lvalues, . , write.

C99 . C99 , lvalues.

write(fd, (char[]) { 1 }, 1)

C99.

+10

, . C, , / .

(, @rob, char. .)

EDIT: . @AndreyT C99.

+3

, , :

write(fd, "\001", 1);

, , , . :

 SomeType i;
 SomeFUnction(&i);
+3

. , 1 . .

+1

, - .

+1

drprintf(), . fprintf(), FILE *.

int dprintf(int fd, const char *format, ...);

. man 3 dprintf.

dprintf() vdprintf() ( glibc2) fprintf (3) vfprintf (3), , fd stdio.

POSIX.1, .

0
write(var, new int(4))

It seems to work. Not sure how good this is since I haven't used C ++. Let me know if this is a bad way to do it.

0
source

All Articles