I am not able to understand the output of the following C code :
#include<stdio.h>
main()
{
char * something = "something";
printf("%c", *something++); // s
printf("%c", *something); // o
printf("%c", *++something); // m
printf("%c", *something++); // m
}
Please help :)
See http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence for details
printf("%c", *something++);
Gets the char at *something and then increments it ('s')
printf("%c", *something);
Just get the char (now the second, due to the increment in the last statement ('o')
printf("%c", *++something);
increment and then get the char of the new position ( 'm' )
printf("%c", *something++);
Gets the char at *something and then increments it ('m')
It is pretty simple.
char * something = "something";
Assignment of pointer.
printf("%c\n", *something++);//equivalent to *(something++)
Pointer is incremented but the value before increment is dereferenced ans it is post-increment.
printf("%c\n", *something);//equivalent to *(something)
Pointer is now pointing to 'o' after increment in the previous statement.
printf("%c\n", *++something);//equivalent to *(++something)
Pointer is incremented to point to 'm' and dereferenced after incrementing the pointer as this is pre-increment.
printf("%c\n", *something++);//equivalent to *(something++)
Same as the first answer.
Also notice '\n' at the end of every string in printf. It makes the output buffer flush and makes the line print. Always use a \n at the end of your printf.
You may want to look at this question as well.
// main entrypoint
int main(int argc, char *argv[])
{
char * something = "something";
// increment the value of something one type-width (char), then
// return the previous value it pointed to, to be used as the
// input for printf.
// result: print 's', something now points to 'o'.
printf("%c", *something++);
// print the characer at the address contained in pointer something
// result: print 'o'
printf("%c", *something);
// increment the address value in pointer something by one type-width
// the type is char, so increase the address value by one byte. then
// print the character at the resulting address in pointer something.
// result: something now points at 'm', print 'm'
printf("%c", *++something);
// increment the value of something one type-width (char), then
// return the previous value it pointed to, to be used as the
// input for printf.
// result: print 's', something now points to 'o'.
printf("%c", *something++);
}
Result:
somm
always use the clockwise rule clockwise rule
printf("%c\n", *something++);
according to the rule you will first encounter * so get the value then ++ means increment
in the 3rd case printf("%c\n", *something++);
so according to the image increment the value ++ and then get the value *
Related
#include<stdio.h>
int main()
{
char *s="Peace";
printf("%s\n",s);
printf("%s\n",s+1);
printf("%s\n",s++);
}
Output:
Peace
eace
Peace
My query is while I did s++ it should have print "eace" instead of "Peace". Why is this happening?
Another question is char *s="Peace"; this line stores the string literal in an anonymous array so when s points to 'P' but when I only printf("%d\n",s); wrote this how could it able to print all the string? shouldn't it print only "P"?
s++ is the post-increment operation. It returns the current value of s then increments s. To get what you want you need to use pre-increment, ++s.
Your evaluation of s++, the increment is after the valuation. If you wish your increment to be before your use then you should be using ++s. Changing this small bit will result in your desired output.
Try this:
char *s="Peace";
int counter;
for (counter=0;counter<=strlen(s);++counter)
{
printf("%s\n",s+counter);
}
Lets decode it line by line:
char *s="Peace";
here s points to 'P'
printf("%s\n",s);
Prints entire string "Peace" as s is at 'P'. That's what %s does actually.
printf("%s\n",s+1);
Now s is at 'e' , so it will print "eace".
printf("%s\n",s++);
This would also print "eace" as you've used a post increment operator. If you had used ++s instead then it would print "ace".
char *s;
char buf [] = "This is a test";
s = strchr (buf, 't');
if (s != NULL)
printf ("found a 't' at %s\n", s);
printf("%c\n",*s);
printf("%c\n",*s++);
printf("%c\n",*s++);
printf("%c\n",*s++);
printf("%c\n",*s++);
This code outputs:
found a 't' at test
t
t
e
s
t
Program ended with exit code: 0
In my view, *s should be t and *s++ should be e. But why they have same value in this code ?
In the expression *s++, ++ is the post-increment operator. That means following happens, in-order:
The value of s is gotten
Then s is incremented
Then the old value of s is de-referenced
So,
printf("%c\n",*s); // Prints the character at s
printf("%c\n",*s++); // Prints the character at s
// ***and then*** increments it
They will both print the same character.
If you want your example code to behave like you think it should, simply remove the first printf without the post-increment on s:
// s points to the 't'
printf("%c\n",*s++); // Prints 't'. Afterward, s points to the 'e'
printf("%c\n",*s++); // Prints 'e'. Afterward, s points to the 's'
printf("%c\n",*s++); // Prints 's'. Afterward, s points to the 't'
printf("%c\n",*s++); // Prints 't'. Afterward, s points to the NUL terminator
printf("%c\n",*s++);
is (more or less1) equivalent to
printf("%c\n",*s);
s++;
This is why you see 't' printed twice.
The expression i++ evaluates to the current value of i, and as a side effect increments the variable.
1. More or less because s will be updated after *s is evaluated, but before printf is actually called. Exactly when the side effect of ++ is applied isn't specified, apart that it happen before the next sequence point. In this case, a sequence point occurs after all function arguments have been evaluated and before the function is called.
char alpha[] = "abcdefghi";
char ch[80], *pch = &ch[0];
strcpy(ch, alpha);
putchar(*pch++);
putchar((*pch)++);
putchar(*++pch);
putchar(++(*pch));
printf("\n%s", ch);
Why does the putchar function print 'a' 'b' 'c' and 'd' respectively?
Why does printf("\n%s", ch); print acddefghi?
I am really bad with pointer stuff.
OK, I will try to explain this as simply as I can.
When you do: putchar(*pch++) what you say is 'print that character of the address that pch points to and then increment the pch to point to the next address'. Essentially, before the first putchar(), *pch = 'a' and after *pch = 'b'(because pch points now to ch[1]).
Now, in the second putchar() what you say is: 'print the character in the address that pch points to and then increment the value of the CHARACTER, in that address, by 1'. So, instead of doing what you did in the second putchar(), you could replace this line whith these two lines:putchar(*pch); // 'b'
*pch += 1; // see, you increment the value(notice the *), not the pointer.
However, because as I said, it increments the character AFTER the second putchar(), it just prints what it was which is 'b'. So, just to clear, after the second putchar(), ch[0] = 'a'(we did not change anything in this value)
and ch[1] = 'c'(we incremented the value of the character by 1 and 'b' + 1 = 'c'). The rest is unchanged, so ch[2] = 'c', ch[3] = 'd' and so on.. but pch points to ch[1]
Now, in the third putchar(), you do something similar with the first except that you first increment the address that pch points and then print the value of this address.So, you could replace the third putchar() with these two lines:pch++; // increment the pointer by one, it now points to ch[2], which is 'c'(it remained unchanged)
putchar(*pch); // 'c'
So, after the third putchar(), ch[0] = 'a'(remained unchanged), ch[1] = 'c'(changed in the second putchar()), ch[2] = 'c'(remained unchanged)
Finally, in the last putchar(), what you do is similar to the second except that you increment the value of the CHARACTER that pch points to before you print it.
Remember that pch points to ch[2]
So, you could replace the last putchar() with these two lines:
*pch += 1; // 'c' + 1 = 'd'
putchar(*pch); // 'd'
So, after the 4 putchars, ch[0] = 'a'(it remained unchanged), ch[1] = 'c'(changed in the second putchar()), ch[2] = 'd'(changed in the fourth putchar()) and ch[3] = 'd'(it remained unchanged) and the rest of the string remains unchanged, and I think it is now obvious why you get the result you get from printf().
ch is an array of characters. In C an array is just a pointer to the first element in the array. That makes ch a pointer to a char (char *) as well. putchar prints a single character when you pass it a character to print. *pch++ says 'use the character at this address' then increment the address to point at the next char. printf prints the whole string because of the format specifier "\n%s" which tells printf to print the array of characters (a string if you will) which is found at the address ch. Which we know from above is an array of characters. Hope this helps.
Dereferences the pointer and returns back the value 'a', then the pointer is incremented by 1.
putchar(*pch++);
Same as the first explanation above. Returns back 'b'.
putchar((*pch)++);
Increments the pointer then dereference it, the value returned back is 'c'.
putchar(*++pch);
Same as the previous, returns back the value of 'd'.
putchar(++(*pch));
Pointer increments/decrements are based on the type of the variable that is declared.
Since ch is declared an array of characters, printf prints out the entire contents of that said variable.
strcpy(ch, alpha);
Copy the contents of alpha into an array ch, i.e. "abcdefghi"
All "arrays" decay into pointers pointing to the first element of type T.
(They are not really arrays!)
value of address means address location
value of data means the value in that address
Try to think it in this way:
Whatever follows after * is an address.
Eg: *x, here the value of x is an address.
And when you combine * and x i.e. *x, it represents the value at that address.
Whenever you do *p++, the value of p( which is address value) post increments by depending on the data type of the pointer. So, it will point to the next block of address. It won't increment the value of data.
In C, the char pointer points to address of first array and prints the entire array until a null character is received.
Watch lectures on pointer. You will be clear.
*pch++ print current pointer value and increments pointer
(*pch)++ print current pointer value, and increments that value
*++pch It increments pointer and print value of new pointer
++(*pch) It increments value of current pointer and then print that new value
putchar(*pch++); // It prints ch[0], print and increments pointer
putchar((*pch)++); // It prints ch[1], print and increment value;
putchar(*++pch); // It prints ch[2], pointer increments and print
putchar(++(*pch)); // It prints ch[2]+1, increment value and print
I have a stored a string in a pointer variable which has memory in heap section. When I print the string character by character the first element is skipped.
Example: if char *p="hello" when i print character by character using while(*p++) loop 'h' is skipped and output is "ello" please can any one explain it?
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *p=(char*)malloc(sizeof(char)*20);
printf("enter string\n");
scanf("%s",p);
while(*p++)// value is assign and address is increased
{
printf("%c",*p);//why first character is skipped??
}
return 0;
}
To see the first letter, change *p to p[-1], because p++ has already incremented p, so by the time you first use *p, p already points to the 2nd letter (with index 1).
There are many other ways to solve it, e.g.
for (; *p; ++p) {
putchar(*p);
}
Because while(*p++) increments the value as soon as the loop starts. By the time the printf statement is reached, p has already been incremented.
p = 0
while(p++) { // p = p + 1
printf('%d', p); // p = 1 when this executes
}
while(*p++) after this statement p is incremented and moved ahead. So at printf() p already points to 2nd character.
The line while(*p++) will check the value of *p and then increment p, before entering the body of the loop. You can improve the code by using a for loop
for ( ; *p; p++ )
printf( "%c", *p );
or by incrementing the pointer after using it, in the body of the loop
while(*p)
printf( "%c", *p++ );
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Can someone explain this reverse sentence code for me? How does the first and the second looping works? What's the point of each of them?
main(){
char arr[255], *p;
printf("Enter string: ");
gets(arr);
for(p=arr; *p!='\0'; p++);
for(p--; p>=arr; p--){
printf("%c",*p);
}
}
Input:
I love you
Output:
uoy evol I
The code is basically printing in reverse the input array.
for(p=arr; *p!='\0'; p++);
Sets p as the last (relevant) element of the array (the null character)
for(p--; p>=arr; p--){
printf("%c",*p);
}
starts from the last (none null) character and prints each one from last to first.
Question for you:
What happens if the input array is longet than 255 chars? (answer below)
buffer overflow
Suppose the input is Hello World. This gets stored in your buffer arr as
[H][e][l][l][o][ ][W][o][r][l][d][\0]...
Your pointer is set to arr, hence the pointer points to H
[H][e][l][l][o][ ][W][o][r][l][d][\0]...
^
|
p
The first loop advances (p++) until it meets the first null character (\0). It now looks like
[H][e][l][l][o][ ][W][o][r][l][d][\0]...
^
|
p
Now the second loop goes back (p--) until it reaches the first character again (actually, until the pointer equals the pointer to the beginning of the array), printing each character as it meets it. The first character \0 however is ignored with the little p-- here:
for(p--; p>=arr; p--)
^^^
The code looks clever, but it actually exhibits undefined behavior, which means the code may do anything.
The problem is the second loop:
for(p--; p>=arr; p--){
printf("%c",*p);
}
What it's intended to do is to start p at the last character of the string (excluding the terminating \0, then keep decrementing it until all the characters of the string have been output in reverse order.
The problem is the termination condition: after the intended end of the loop, p is arr, and then p-- subtracts one, and then p >= arr is false.
Unfortunately, an arithmetic operation on pointers may not result in a pointer that no longer points to the object (or one after the final object of an array), or it's undefined behavior.
That's what's happening here: p-- causes p to be off the array, and all bets are off as to what happens next.
Here's a correct way to write the second loop:
for (int i = (p-arr)-1; i >= 0; i--) {
printf("%c", p[i]);
}
I'd probably write the entire code using indexes to completely avoid pointer arithmetic. Maybe something like this:
int i = 0;
// Find the terminating \0 byte
while(p[i])i++;
// Iterate backwards through the string, outputting characters along the way.
while(--i >= 0)putc(p[i]);
Before explaining the code, I must say two things - first, the signature of the main function should be one of the following -
int main(void);
int main(int argc, char *argv[]);
and second, do not use gets. It's not safe to use. Use fgets instead. Now, coming to the code.
for(p = arr; *p != '\0'; p++) ;
In the above loop, p is assigned the base address of the array arr, i.e., the address of the first element of the array arr. The array arr contains a terminating null byte which means it is a string. The loop body is the null statement ; which means p is incremented till the null byte is encountered, i.e., when the test *p != '\0' fails. In the for loop
for(p--; p >= arr; p--) {
printf("%c",*p);
}
p is first decremented to point to the last character just before the null byte and then it is printed in each iteration till the condition p >= arr is true, i.e., till the first element of the array is reached. You should change your code to -
#include <stdio.h>
int main(void) {
char arr[255], *p;
printf("Enter string:\n");
fgets(arr, sizeof arr, stdin);
for(p = arr; *p! = '\0'; p++)
; // the null statement
for(p--; p >= arr; p--)
printf("%c", *p);
return 0;
}