简体   繁体   English

无法在C中为“ const char * const * my_array”赋值

[英]can't assign value to “const char * const *my_array” in C

Bellow is my C code: 贝娄是我的C代码:

const char *l = "some text";
const char * const *m = {l};

When I try to compile that code, I get this warning: 当我尝试编译该代码时,收到以下警告:

warning: initialization from incompatible pointer type 警告:从不兼容的指针类型初始化

Can anybody explain me why that warning and how should I initialize the second variable ( m )? 谁能解释我为什么发出该警告,以及如何初始化第二个变量( m )?

Actually, you are not using the const keyword in the right way. 实际上,您没有以正确的方式使用const关键字。 const applies to the first left token it meets or, if there is not, to the first right token. const适用于它遇到的第一个左令牌,如果没有,则适用于第一个右令牌。

So, in your case : 因此,在您的情况下:

const char * const *m;

The first const applies to char , just like for l . 第一个const适用于char ,就像l The second one applies to your first * , which means that m is a pointer to a constant pointer to a constant content ("some text"). 第二个适用于您的第一个* ,这意味着m是指向常量内容(​​“某些文本”)的常量指针的指针。 Since you had not written 既然你还没写

const char * const l;

There is a conflict with the const-ness of your two pointers hence the warning. 您的两个指针的一致性存在冲突,因此发出警告。

I think what you want is to guarantee that the address stored in l won't be altered by the program. 我认为您想要的是保证程序中不会更改l存储的地址。 If it is that so, then you must change the declaration of l to this one : 如果是这样,则必须将l的声明更改为以下声明:

const char * const l = "some text";

Why not use 为什么不使用

const char* m[] = {l};

I think that should work. 我认为应该可以。

I imagine you actually intend m to be more than one element long, otherwise you would not do something so convoluted, right? 我想您实际上打算将m长度超过一个,否则您将不会做那么复杂的事情,对吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM