【发布时间】:2016-09-18 10:42:20
【问题描述】:
#include<stdio.h>
#include<iostream>
#include<cstring>
using namespace std;
int main(void)
{
char a[10]="Rosewater";
char b[3];
int i=0;
for(i=0;i<5;i++)
{
b[i]=a[i]; //1. does not throw an error
}
printf("%s\n%s\n",a,b);
}
输出:
ewsewater // value of a also changed
Rosewsewater // unclear output
【问题讨论】:
-
你有未定义的行为。
-
您的代码写到了
b的末尾,从而导致了未定义的行为。未定义的行为可能会导致错误,但并非必须如此。 -
是的,我明白了.. 但它如何改变字符串 a 的值?那应该保持原样..
-
“未定义的行为”意味着任何事情都可能发生,并且没有定义的结果。这可能是一个段错误。这可能是该程序的明显正确结果。每次程序运行时,结果都可能不同。
-
@SumitKumar 只要本网站(或其他地方)上的某个人说您的程序调用了未定义的行为(“UB”),您就无法推断“应该”发生什么。这就是语言给你 undefined 行为的意义所在,is 没有“应该”。