C 编程 - 将变量参数传递给 opendir
我正在尝试这样做:
const char *p = "/home/paul";
dp = opendir(*p);
但是失败并出现以下错误:
传递“opendir”的参数 1 使指针来自不带 a 的整数 演员表
,据我所知我正在尝试的是完全有效的。毕竟,我将一个 const char 传递给一个输入是 const char 的函数。 我做错了什么?
I'm trying to do this:
const char *p = "/home/paul";
dp = opendir(*p);
But that fails with the following error:
passing argument 1 of 'opendir' makes pointer from integer without a
cast
I'm at a loss here, as far as I know what I'm attempting is perfectly valid. After all, I'm passing a const char to a function who's input is a const char.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
opendir()
函数接受 < code>const char * 参数,但您向其发送的是const char
。*p
取消引用p,并返回数组中的第一个字符,即“
/
”。因此,*p
的结果是const char
值“/
”。p
但是是一个const char *
,所以将其更改为:The
opendir()
function accepts aconst char *
argument, but you're sending it aconst char
.*p
dereferences the value pointed to byp
, and returns the first character in the array, which is "/
". So the result of*p
is theconst char
value "/
".p
however is aconst char *
, so change that to:您的代码失败,因为您要间接通过 p:
dp = opendir(*p);
因为 opendir 采用 char * 作为参数,并且您告诉 opendir 在 p 指向的位置查找该 char *,所以 opendir 使用“/home/paul”作为其 char *。
但 p 正是 opendir 想要的值。相反,说:
dp = opendir(p);
一切都会像玻璃一样光滑。
Your code is failing because you are going indirect through p:
dp = opendir(*p);
Because opendir takes a char * as an argument, and you are telling opendir to look for that char * in the spot where p is pointing, opendir is using "/home/paul" as its char *.
But p is the exact value opendir wants. Instead, say:
dp = opendir(p);
and everything will be smooth as glass.
声明 const char *p = "/home/paul";意味着 'p' 指向字符串的开头,其中 p 本质上是字符串所在的内存地址。
当你写 *p 时,意味着你正在访问 p 指向的内容,即字符串中的第一个字符,即“/”
the declaration const char *p = "/home/paul"; means that 'p' is pointing to the start of the string where p is essentially an address in memory where the string is.
when you write *p it means you are accessing the content of where p points which is the first character in the string, namely '/'