Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a constant integer when function expects a pointer

What's the best/most cannonical way of passing in a constant integer value to a function that expects a pointer?

For example, the write function

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

Let's say I just want to write a single byte (a 1), I would think this:

write (fd, 1, 1);

but I obviously get the warning

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

I know I can do

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

but is that necessary? What's the most correct way of doing this without the need of declaring/initializing a new variable?

like image 688
Falmarri Avatar asked May 24 '11 21:05

Falmarri


People also ask

Can we pass the constant value from the function?

The constant parameter received by the function can not be changed in the body of the function. This means you can not use an assignment operation in which a constant parameter receives a value.

Can we assign integer value to pointer variable?

Yes you can. You should only assign the address of a variable or the result of a memory allocation function such as malloc, or NULL.

Can we change the value of a constant integer using pointers?

C program to change the value of constant integer using pointers. Since, we cannot change the value of a constant but using pointer we can change it, in this program we are doing the same.

What happens if you pass a pointer to a function?

Pass-by-pointer means to pass a pointer argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the variable to which the pointer argument points. When you use pass-by-pointer, a copy of the pointer is passed to the function.


1 Answers

In C89/90 you can't generally do it without declaring a new variable. The thing about pointers in C is that they always point to lvalues. Lvalue is something that has a location in memory. So, in order to supply the proper argument to your function, you need something that has a location in memory. That normally requires a definition, i.e. an object, a variable. Constants in C are not lvalues, so you can't use a constant there. Things that lie somewhat in between constants and variables are literals. C89/90 has only one kind of literal: string literal. String literals are lvalues, but not variables. So, you can use a string literal as the second argument of write.

In C99 the notion of literal was extended beyond string literals. In C99 you can also use compound literals for that purpose, which also happen to be lvalues. In your example you can call your function as

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

But this feature is only available in C99.

like image 180
AnT Avatar answered Nov 15 '22 06:11

AnT