对"i"的操作可能未定义 [英] operation on 'i' may be undefined

查看:120
本文介绍了对"i"的操作可能未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码可以采用bla_2形式的字符串并将其分开:

void separate(char* str, char* word, int* n) {
    int i = 0;
    while(str[i] != '_') {
        word[i] = str[i++];
    }
    *n = str[++i] - '0';
}

我得到了:

warning: operation on ‘i’ may be undefined [-Wsequence-point]

但是我只通过++运算符更改i,没有分配任何内容.

那么,为什么要使用UB?如果没有,该如何消除警告?

请注意,我认为问题处理的是另一个问题.

解决方案

word[i] = str[i++];是一个问题.

str[i++];中的i递增之前或之后,是否访问word[i]中的i是编译器的选择.

分配后执行i++

word[i] = str[i];
i++;


更多while(str[i] != '_')应该是

while(str[i] != '_' && str[i] != '\0')

防止缓冲区溢出.

I have this code to take a string of the form bla_2 and separate it:

void separate(char* str, char* word, int* n) {
    int i = 0;
    while(str[i] != '_') {
        word[i] = str[i++];
    }
    *n = str[++i] - '0';
}

I got:

warning: operation on ‘i’ may be undefined [-Wsequence-point]

But I am only changing i via ++ operator, I am not assigning anything to.

So, why is the UB, if it is? If not, how to get rid of the warning?

Notice that in my opinion, this question handles a different issue.

解决方案

word[i] = str[i++]; is a problem.

It is compiler's choice if i in word[i] is access before or after i is incremented in str[i++];

Do the i++ after the assignment

word[i] = str[i];
i++;


Further while(str[i] != '_') likely should be

while(str[i] != '_' && str[i] != '\0')

to prevent buffer overrun.

这篇关于对"i"的操作可能未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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