C Programming - Strings - Discussion

Discussion Forum : Strings - Find Output of Program (Q.No. 23)
23.
What will be the output of the program ?
#include<stdio.h>

int main()
{
    char str[] = "Nagpur";
    str[0]='K';
    printf("%s, ", str);
    str = "Kanpur";
    printf("%s", str+1);
    return 0;
}
Kagpur, Kanpur
Nagpur, Kanpur
Kagpur, anpur
Error
Answer: Option
Explanation:

The statement str = "Kanpur"; generates the LVALUE required error. We have to use strcpy function to copy a string.

To remove error we have to change this statement str = "Kanpur"; to strcpy(str, "Kanpur");

The program prints the string "anpur"

Discussion:
24 comments Page 3 of 3.

Vijayakumar said:   8 years ago
No, it won't produces the error, the string can be assigned directly using = during the initialization. So the answer will be C).

Murphy said:   8 years ago
Guys, the answer D is correct but the official explanation is horribly wrong!

This line is problematic:

"str[0]='K';"
The reason is, a literal string like "Nagpur" is stored in static memory area, READ ONLY. You can not change the value.

There is no problem to assign to str a different literal string because it is a char pointer, that is what a point is born to do.

Try run the code yourself, comment all lines after "str[0]='K';" and see what you find out.

Utkarsh said:   6 years ago
"String" is not a data type in C (unlike python, Java etc.) so you cannot simply assign:

char name[20];
name = "market"; // wrong
name[0] = "cricket"; // wrong again

"cricket" is called a string literal whereas name is a char array, i.e {'c','r','i','c','k','e','t','\0'}. They are not automatically converted to each other - you have to write your own function to copy char-by-char or use the library function strcpy().

Then how is;
char name[20] = "This is me";
valid code? Well, this is just a C short-cut for writing
char name[20] = {'T','h','i','s',' ','i','s',' ','m','e','u','\0'};

It does not work anywhere else.

Please, anyone, explain clearly.

Mayur said:   4 years ago
#include<stdio.h>

int main()
{
char str[] = "Nagpur";
str[0]='K';
printf("%s, ", str);
*str = "Kanpur";
printf("%s", str+1);
return 0;
}

This Gives O/P - Kagpur, agpur.

So We cannot just assign a value directly to the base address, We have to dereference to do that.


Post your comments here:

Your comments will be displayed after verification.