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;
}
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 2 of 3.
Krti said:
1 decade ago
What is mean by lvalue required error?
Akhilesh said:
1 decade ago
char str[] = "Nagpur";
str = "Kanpur";
Here str is a constant pointer and it is pointing to a string "Nagpur" (that is an array of char type).
In the second line we are trying to override the array which is not possible. we can assign it character by character. There is a inbuilt function strcpy(str,"Kanpur") that can be used for direct copying(overriding).
str = "Kanpur";
Here str is a constant pointer and it is pointing to a string "Nagpur" (that is an array of char type).
In the second line we are trying to override the array which is not possible. we can assign it character by character. There is a inbuilt function strcpy(str,"Kanpur") that can be used for direct copying(overriding).
Dheeraj Pandey said:
1 decade ago
If we use strcpy(str,"kanpur")like this... then what will the output.
#include<stdio.h>
int main()
{
char str[] = "Nagpur";
str[0]='K';
printf("%s, ", str);
str = strcpy(str,"Kanpur");
printf("%s", str+1);
return 0;
}
#include<stdio.h>
int main()
{
char str[] = "Nagpur";
str[0]='K';
printf("%s, ", str);
str = strcpy(str,"Kanpur");
printf("%s", str+1);
return 0;
}
# G.S. said:
1 decade ago
To copy a string we cant do it directly . For this we having the inbuilt function strcpy(,).
So here , If we want to put the "Kanpur" to str, we have to do like this strcpy(str, "Kanpur");
Otherwise its a ERROR.
So here , If we want to put the "Kanpur" to str, we have to do like this strcpy(str, "Kanpur");
Otherwise its a ERROR.
Sarita said:
1 decade ago
Str="kanpur" str is consider as base address and we can not change value of base address hence error.
Nsk said:
1 decade ago
initially str[]=Nanpur...but when strcpy(str, "Kanpur"),the content of str[]=Kanpur will overwrite Nagpur.Since str represent base address str+1 will point to second character a & print the character starting from a to r i.e anpur
Ravi said:
1 decade ago
I don not understand, please give me another example.
Honey said:
1 decade ago
Am not understanding, please explain it in easy way.
Raj said:
1 decade ago
Please give some other example !
Kiran said:
1 decade ago
It is not understanding. Please explain it in other ways.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers