为什么这个允许(字符*)至(为const char *)推广? [英] Why does this allow promotion from (char *) to (const char *)?

查看:140
本文介绍了为什么这个允许(字符*)至(为const char *)推广?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于scanf函数有来自微软文档中(为const char *)一>和答案<一个href=\"http://stackoverflow.com/questions/766290/shouldnt-it-be-permissible-to-convert-from-char-to-const-char\">this问题中究竟发生了什么会,当我做了(字符**)推广到相同(为const char **)?

Given that scanf has (const char *) in the documentation from Microsoft and the answer to this question what the heck is going when I do the same for (char **) promotion to (const char **)?

基本上,为什么会发生这种编译?

Basically why does this compile?

#include <stdio.h>
int main(int argc, char **argv)
{   
    char szArray[50];
    int  i = 0;
    strcpy(szArray,"10");
    /* the following code is upcasting the (char *) to (const char *) */
    sscanf(szArray,"%d",&i);
    return 0;  
}

为什么不会在编译?

And why won't this compile?

#include <stdio.h>
void processargs(const char **p)
{ 
}
int main(int argc, char **argv)
{
    processargs(argv);          
    return 0;  
}

似乎都在做同样的事情的指针!

Both seem to be doing the same thing to a pointer!

推荐答案

的char ** - &GT;为const char ** 是危险的,因为你可能最终意外地修改基础常量对象。

char** -> const char ** is dangerous, since you might end up accidentally modifying the underlying const object.

写你想要什么正确的方法是:

The correct way to write what you want is:

void processargs(const char * const *p)
{ 
}

这篇关于为什么这个允许(字符*)至(为const char *)推广?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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