当函数需要指针时传递一个常量整数 [英] Passing a constant integer when function expects a pointer

查看:318
本文介绍了当函数需要指针时传递一个常量整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将常量整数值传递给期望指针的函数的最好的/最大胆的方法是什么?

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

例如,函数

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

假设我只想写一个字节(a 1),我会这样认为: / p>

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

write (fd, 1, 1);

但我明显得到警告

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


$ b b




我知道我可以做


I know I can do

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

但这是必要的吗?

推荐答案

在C89 / 90中,你可以使用一个新的变量,通常不做声明新变量。关于C中的指针的事情是,他们总是指向lvalue。 Lvalue是在内存中有一个位置的东西。所以,为了给你的函数提供正确的参数,你需要一些在内存中有位置的东西。这通常需要一个定义,即一个对象,一个变量。 C中的常量不是左值,所以你不能使用常量。在常量和变量之间的某些事情是字面量。 C89 / 90只有一种文字:字符串文字。字符串字面量是lvalue,但不是变量。因此,您可以使用字符串文字作为 write 的第二个参数。

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.

在C99中,文字的概念是扩展超出字符串字面量。在C99中,您也可以使用复合文字来达到目的,这也是左值。在你的例子中,你可以调用你的函数

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)

但此功能仅在C99中可用。

But this feature is only available in C99.

这篇关于当函数需要指针时传递一个常量整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆