INTERVIEW QUESTIONS
C
STRINGS IN C
DETAILS
Question: What is wrong with the following c program? char *s1 = "hello"; char *s2 = "world"; char *s3 = strcat(s1, s2);
Please provide me explanations??
Answer: Since what is present in memory beyond "United" is not known and we are attching "Front" at the end of "United", thereby overwriting something, which is an unsafe thing to do.
|
Question:
What is wrong with the following c program? char *s1 = "hello"; char *s2 = "world"; char *s3 = strcat(s1, s2);
Please provide me explanations??
Answer:
Since what is present in memory beyond "United" is not known and we are attching "Front" at the end of "United", thereby overwriting something, which is an unsafe thing to do. Source: CoolInterview.com
see the declarations You have specified here. char *s1="hello"; char *s2="world"; Now U self check whether you get the same output hello for gets(s1); (or else) printf("%c",s1);
Definitely No.
Because *s1 is different from s1.
we know &(*s1)=s1.Here You are calling the address of s1 but not the actual *s1. So try to change it as
strcat(*s1,*s2);
Source: CoolInterview.com
Answered by: kalavnagarjuna | Date: 3/21/2008
| Contact kalavnagarjuna
char *s1="hello"; char *s2="world"; char *s3=strcat(s1, s2); here, we are not allocating the memory to the s3. so givs "Segmentation Fault". And that to we cant not assign the strcat val to s3, as strcat returns a pointer to the resulting dest string, which is s1 here. Source: CoolInterview.com
Answered by: Santosh | Date: 2/4/2009
| Contact Santosh
This code will not work. Because the strings "hello" and "world" are stored in data section and their starting address will be assigned to pointers. Since strcat appends the second string at the end of the first string and the address after hello is only readable or may not be in our process address space it gives Segmentation Fault when executed.
Changing this code snippet to the following will work:
char s1[20] = "hello"; char *s2 = " world"; char *s3 = strcat(s1,s2); Source: CoolInterview.com
Answered by: Vemula Venugopal | Date: 4/21/2009
| Contact Vemula Venugopal
If you have the better answer, then send it to us. We will display your answer after the approval.
Rules to Post Answers in CoolInterview.com:-
- There should not be any Spelling Mistakes.
- There should not be any Gramatical Errors.
- Answers must not contain any bad words.
- Answers should not be the repeat of same answer, already approved.
- Answer should be complete in itself.
|