C Programming - Strings - Discussion
Discussion Forum : Strings - Find Output of Program (Q.No. 2)
2.
What will be the output of the program ?
#include<stdio.h>
int main()
{
char p[] = "%d\n";
p[1] = 'c';
printf(p, 65);
return 0;
}
Answer: Option
Explanation:
Step 1: char p[] = "%d\n"; The variable p is declared as an array of characters and initialized with string "%d".
Step 2: p[1] = 'c'; Here, we overwrite the second element of array p by 'c'. So array p becomes "%c".
Step 3: printf(p, 65); becomes printf("%c", 65);
Therefore it prints the ASCII value of 65. The output is 'A'.
Discussion:
12 comments Page 1 of 2.
John said:
1 decade ago
@Rishi.
char p[] is an array that having each array value.
p[0]=%
p[1]=d
p[2]=\
p[3]=n
then p[1]=d=c and printf("%d\n",65);
printf will change to printf("%c\n",65);
Now printf can print only character value(as of %c) finally print ASCII value of 65=A.
char p[] is an array that having each array value.
p[0]=%
p[1]=d
p[2]=\
p[3]=n
then p[1]=d=c and printf("%d\n",65);
printf will change to printf("%c\n",65);
Now printf can print only character value(as of %c) finally print ASCII value of 65=A.
(3)
Monish said:
8 years ago
Since array gets a place in stack section so it can be modified hence we can change its value and as you are saying char p[] is not a string literal if you want to make it a string literal then give it as character pointer which can't be modified further.
Monish Dadwal said:
8 years ago
It is an array so it is stored in stack section, in case you are saying string literal then you need to give it as a character pointer since character pointer gets its place in string literal which can't be modified.
Karthik said:
1 decade ago
Is it possible to change content of char ?
In above program p[1] = d.
p[1] = c has been changed.
If is it possible what is use strcpy() function ?
In above program p[1] = d.
p[1] = c has been changed.
If is it possible what is use strcpy() function ?
Xcoder said:
1 decade ago
@Karthik.
I think at a time we can change one value store in specific location.
But by using strcpy() can replace whole string;.
I think at a time we can change one value store in specific location.
But by using strcpy() can replace whole string;.
Rahul said:
5 years ago
Inside p base address will be present, then how p inside gives "%c\n". Rather it should give the only % ? Am I right?
Siri said:
10 years ago
char p[] contains a string literal. How can we change the value in it?
Hassan said:
8 years ago
But what about "\n" why that's not elements of the array?
Rishi said:
1 decade ago
How p becomes %c in the last printf statement?
Megha said:
1 decade ago
/ & n is not a character in string array.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers