加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

字符数组下标警告

发布时间:2020-12-16 03:27:07 所属栏目:百科 来源:网络整理
导读:当我在这个例子中使用char数组下标时: int main(){ char pos=0; int array[100]={}; for(pos=0;pos100;pos++) printf("%in",array[pos]); return 0;} 我收到警告,我正在使用char数组下标: warning: array subscript has type ‘char’ [-Wchar-subscripts
当我在这个例子中使用char数组下标时:
int main(){
    char pos=0;
    int array[100]={};

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

    return 0;
}

我收到警告,我正在使用char数组下标:

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

哪个好,因为我启用了此警告.

GCC手册说:

-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.

因此,此警告应防止使用负数组索引.我的问题是,为什么此警告仅在char上有效,而在其他已签名类型上无效?

谢谢.

解决方法

这是因为int始终是签名的.

char不必.

char可以是签名或未签名,具体取决于实现. (有三种不同的类型 – 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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读