passing arg 1 of `foo' from incompatible pointer type

醉酒当歌 提交于 2019-12-02 20:54:09

问题


Why this shows warning:

#include<stdio.h>
foo (const char **p)
{ 

}

int main(int argc , char **argv)
{
    foo(argv);
}

But following does not show any warning

char * cp;
const char *ccp;
ccp = cp;

The first code snippet shows warning passing arg 1 of foo from incompatible pointer type. But the second snippet does not show any warning. Both are const pointers


回答1:


See the C FAQ list

You can cast in order to remove warnings:

foo((const char **)argv);

But as FAQ says: the need for such a cast may indicate a deeper problem which the cast doesn't really fix.




回答2:


Depending on your compilation flags, you might need an explicit cast when assigning cp's content to ccp.




回答3:


In the first version you are casting between two different types of pointer not simply adding a const to the pointer.

  • char ** is a pointer to a (pointer to a char)
  • const char ** is a pointer to a (pointer to a const char)

As you can see these pointer point to different types similar to the more obviously questionable:

int *i;
double *d;
d = i;

In your second example you see that you can cast from a pointer to a const pointer so if you were to apply this to your situation you would need to have a const pointer to (a pointer to a char).

foo(char * const *p);


来源:https://stackoverflow.com/questions/16542641/passing-arg-1-of-foo-from-incompatible-pointer-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!