假设 scanf 在 documentation from Microsoft 中有 (const char *)以及 this question 的答案当我将 (char **) 提升为 (const char **) 时,到底发生了什么?
基本上为什么要编译?
#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;
}
为什么不能编译?
#include <stdio.h>
void processargs(const char **p)
{
}
int main(int argc, char **argv)
{
processargs(argv);
return 0;
}
两者似乎都在对指针做同样的事情!
最佳答案
char** -> const char **
是危险的,因为您最终可能会不小心修改底层的 const
对象。
正确的写法是:
void processargs(const char * const *p)
{
}
关于c - 为什么这允许从 (char *) 提升到 (const char *)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/766386/