edited by
576 views
2 votes
2 votes

What does the following fragment of c program print?
#include<stdio.h>
#include<string.h>
void main()
{
char q[]="madeeasy2016";
char *p=q+4;
strcpy(p,"best");
printf("%s",q);
}

a. madeeasy2016
b. madebest
c. madebest2016
d. None of these

edited by

3 Answers

Best answer
9 votes
9 votes

Let's suppose the starting address of the array is $200$. Then array $q$ is stored like $\Rightarrow$

Now, $*p = q+ 4$ means p stores the address $204$, Now strcpy() function writes the string $q$ staring from address $204$ with string best. and the string q becomes $\Rightarrow$

printf("%s",q); prints string $q$ till it sees NULL character.So, madebest is printed here.

edited by
2 votes
2 votes
p will contain the string from 5th character(start from 0th position in q) so p contains "easy2016"..  now strcpy will copy "best" to p.. and adds a null character at the end.. since % s prints till the null character it will print "madebest"..
1 votes
1 votes
char * strcpy ( char * dest, const char * src );

Copies the string pointed by src into the array pointed by dest, including the terminating null character.

#include <stdio.h>
#include <string.h>
int main() {
    char q[] = "madeeasy2016";
    char *p = q+4;


/* String literal "madeeasy2016" is lying somewhere in the read-only area of memory. 
q is pointing to the address of 'm' and now p is pointing to the address of second 'e'
*/
    printf("%s\n",p);
    /* easy2016 will be printed */
    
    strcpy(p,"best");
    printf("%s\n",q);
    return 0;
}


 

So, madebest will be printed.

edited by

Related questions

2 votes
2 votes
1 answer
1
0 votes
0 votes
1 answer
2
Markzuck asked Jan 10, 2019
496 views
Please explained detialed execution of this code, I am not getting how int stored in char, like we can interchange using ASCII but still cant store right?
1 votes
1 votes
0 answers
4