Jul 16, 2013 at 8:55am UTC
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
char * str;
char * str2;
char b[6] ;
b[0] = 'H';
b[1] = 'e';
b[2] = 'l';
b[3] = 'l';
b[4] = '0';
b[5] = '.';
char c[] = "Hello." ;
str = b ;
str2 = c ;
cout << str << endl ;
cout << str2 << endl ;
return 0;
}
The programs's output is
Hell0.ëş(
Hello.
But when I move "char c" above main method (as Global)
#include <iostream>
#include <iomanip>
using namespace std;
char c[] = "Hello." ;
int main() {
char * str;
char * str2;
char b[6] ;
b[0] = 'H';
b[1] = 'e';
b[2] = 'l';
b[3] = 'l';
b[4] = 'o';
b[5] = '.';
str = b ;
str2 = c ;
cout << str << endl ;
cout << str2 << endl ;
return 0;
}
Program's output is
Hello.
Hello.
Why ? How could "char c" affect another char val 'b'
Jul 16, 2013 at 9:13am UTC
Your program has an undefined behaviour because array b does not have the terminating zero. So the output depends on what follows array b. To correct the program you should write
b[0] = 'H';
b[1] = 'e';
b[2] = 'l';
b[3] = 'l';
b[4] = 'o';
b[5] = '\0';
In this case the both results will be identical.
Last edited on Jul 16, 2013 at 9:14am UTC