2.What will print out? main() { char p1=“name”; char *p2; p2=(char)malloc(20); memset (p2, 0, 20); while(*p2++ = *p1++); printf(“%sn”,p2); }

  1. name

  2. 0

  3. empty string.

  4. none


Correct Option: C

AI Explanation

To answer this question, let's go through the code step by step:

main() {
    char *p1 = "name";
    char *p2;
    p2 = (char*)malloc(20);
    memset(p2, 0, 20);
    while (*p2++ = *p1++);
    printf("%sn", p2);
}

First, we declare two character pointers p1 and p2.

p1 is assigned the address of a string literal "name".

p2 is allocated memory using malloc(20) and the memory is initialized to 0 using memset(p2, 0, 20).

Next, there is a while loop: while (*p2++ = *p1++). This loop copies the characters from p1 to p2 until it encounters the null character ('\0') at the end of the string.

After the while loop, p2 is pointing to the null character at the end of the copied string.

Finally, printf("%sn", p2) is used to print the contents of p2.

Since p2 is pointing to the null character at the end of the copied string, it will print an empty string.

Therefore, the correct answer is C) empty string.

Find more quizzes: