in Programming edited by
384 views
1 vote
1 vote

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

in Programming edited by
384 views

3 Answers

8 votes
8 votes
Best answer

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

1 comment

nice . correct the typo btw.
1
1
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 vote
1 vote
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
by

Related questions