字符数组下标预警 [英] Char array subscript warning

查看:655
本文介绍了字符数组下标预警的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我用字符数组下标,如下例:

when I use char array subscript as in this example:

int main(){
    char pos=0;
    int array[100]={};

    for(pos=0;pos<100;pos++)
        printf("%i\n", array[pos]);

    return 0;
}

我收到我使用字符数组下标警告:

I am getting warning that I am using char array subscript:

警告:数组下标具有类型'字符'[-Wchar-标]

warning: array subscript has type ‘char’ [-Wchar-subscripts]

这是正常的,因为我已经启用此警告。

Which is OK, because I have this warning enabled.

GCC手册说:

-Wchar-标
      警告如果数组下标具有输入字符。这是错误的常见原因,程序员往往忘记了这种类型的一些签约
  机器。这个警告是被-Wall启用。

-Wchar-subscripts Warn if an array subscript has type "char". This is a common cause of error, as programmers often forget that this type is signed on some machines. This warning is enabled by -Wall.

所以这个警告应该使用$负数组索引的对$ pvent。我的问题是,为什么这个警告只对char活跃,也没有在其他符号类型?

So this warning should prevent of using negative array index. My question is, why is this warning active only on char and not also on other signed types?

感谢您。

推荐答案

这是因为 INT 总是被签署。

字符不就得了。

字符可根据实施符号或无符号。 (有三种不同的类型 - 字符符号字符 unsigned char型

char can be signed or unsigned, depending on implementation. (there are three distinct types - char, signed char, unsigned char)

但是,什么问题?我可以只使用值从0到127这能伤害我默默地?

哦,是的,它可以。

//depending on signedess of char, this will
//either be correct loop,
//or loop infinitely and write all over the memory
char an_array[50+1];
for(char i = 50; i >= 0; i--)
{
    an_array[i] = i;
    // if char is unsigned, the i variable can be never < 0
    // and this will loop infinitely
}

这篇关于字符数组下标预警的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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