对"i"的操作可能未定义 [英] operation on 'i' may be undefined
问题描述
我有这段代码可以采用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屋!