- 1

Why is it giving 'hexa' and not 'he'? (the same output for cpp too)

#include <stdio.h> int main() { //code char str1[]="hexa"; char str2[2]=" "; char *t,*s; s=str1; t=str2; while(*t=*s) *t++=*s++; printf("%s\n",str2); return 0; }

9th Sep 2020, 6:17 PM
Aayu
9 Respuestas
+ 1
No.. Aayu char str1[]="Hexa"; char str2[5]="ui"; char *t,*s; s=str1; t=str2; cout<<*(t+1); //output str2+1 => i *t=*s; //*t =*s = *str1 => H, srr2=Hi cout<<*t; //output H *(t+1)=*(s+1); // s+1 =>str+1 =>'e' to *(t+1), str2=He cout<<*(t+1) ; //output e *(t+2)=*(s+2); //*(s+2) =>str+2 =>x into *(t+2), str2=Hex cout<<(*t+2); //*t = H => *t+2 => 72(ascii value) +2 =74, ( you are not referring to *(t+2)) *(t+3)=*(s+2); //*(s+2) is x. Assigned into *(t+3) = x so str2= Hexx cout<<"\n"<<str2; //this output Hexx
12th Sep 2020, 1:42 PM
Jayakrishna 🇮🇳
+ 1
In c, you can access beyond array length, it won't stop you but warning you only.. And you get garbage values if you not assigned but here your assigning charecter with also \0 at end so it returning assigned value....
9th Sep 2020, 6:29 PM
Jayakrishna 🇮🇳
+ 1
Yes. In c/c++. It only stop you at the time of initialization like char str1[2] = " hexa" ; is error... char str1[3] ="he"; is correct.. but after it won't stop you access beyond initial length but you may not get desired accurate values if you do so..
9th Sep 2020, 7:08 PM
Jayakrishna 🇮🇳
+ 1
~ swim ~ yes. Wrong calculation.. Thanks.. Edited.. But we get correct result because null will added automatically...
9th Sep 2020, 9:34 PM
Jayakrishna 🇮🇳
0
Its returning the same for cpp too.
9th Sep 2020, 7:00 PM
Aayu
0
#include <iostream> using namespace std; int main() { //code char str1[]="Hexa"; char str2[5]="ui"; char *t,*s; s=str1; t=str2; cout<<*(t+1); *t=*s; cout<<*t; *(t+1)=*(s+1); cout<<*(t+1); *(t+2)=*(s+2); cout<<(*t+2); *(t+3)=*(s+2); cout<<"\n"<<str2; return 0; } output iHe74 Hexx is 74 taken as a garbage value?
11th Sep 2020, 8:04 AM
Aayu
0
Jayakrishna🇮🇳 Okay, got it. Thanks a lot 😊.
13th Sep 2020, 3:37 AM
Aayu