Confused with this output in C - c

#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".

Related

Can someone explain me the use of --destination here?

I am completing my CISCO course on C and I got a doubt in the following function.
Can someone please explain me the logic of the function, especially the use of --destination here?
char *mystrcat(char *destination, char *source)
{
char *res;
for(res = destination; *destination++; ) ;
for(--destination; (*destination++ = *source++); ) ;
return res;
}
The first loop is looking for the string teminator. When it finds it, with *destination being false, the pointer is still post-incremented with *destination++.
So the next loop starts by decrementing the pointer back to pointing to the '\0' terminator, to start the concatentation.
In the second loop, each character is copied until the string terminator is found with (*destination++ = *source++); which is evaluated as the loop control. Again, this will include the required string terminator being copied.
This is a very complicated function for something that shouldn't be written so difficult.
--destination is a weird feature of C. I'm assuming you already know that variable++ increments the variable by one. Similarly variable-- decrements the variable by one. The thing is, when the ++ or -- comes after the variable name, that operation is done after the line is executed as a whole, when it is before the variable, C does the arithmetic first, then evaluates the full line.
For an example:
int c = 5
print(c++) -> outputs '5'
print(c) -> outputs '6'
but
int d = 5
print(++d) -> outputs '6'
print(d) -> outputs '6'
This is because in the second example, the increment is evaluated before the entire line is evaluate.
Hope that helps.

while() loop keeps iterating unexpectedly

program
int main()
{
int a=0xabcd;
char *p=&a;
while(p)
{
if(*p=='c')
{
printf("i got %c\n",*p);
return;
}
p++;
}
}
1)why i got always an answer like "i got c".
2)no matter how many times i execute this program, why i got %c as c.
3)replace c character with any character, no matter ,why we got such a character that what we put in if condition?.
if(*p=='z') or if(*p=='t') or ....
4)can anybody explain what was the reason?
int a=0xabcd on a 32 bit machine will give you 0x0000abcd. If you try to read the contents of this integer as a character, you'll either get 0x00 or 0xcd, depending on endianess. Neither is a printable ASCII character. This doesn't make any sense.
while(p) means "while p points at an address which is not zero". This doesn't make any sense. Because of this, you continue to loop and read random memory cells outside the allocated integer. Anything can happen. If you are lucky, the program will crash.
To sum it up, it appears you don't quite know what you are doing...
1) You get i got c because your program has a pointer p that points on each bytes of 0xabcd in sequence and beyond ! At some point, the pointer will point on the byte 0x63 which is 'c'. Since this is the if condition, the print statement prints the char pointed by p and you see the message i got c.
2) because of the if condition that execute the print statement only if the byte pointed by p is 0x63 thus 'c'. This is why you always see the same message. Note however that it only works if there is a byte with value 0x63 somewhere in memory.
3) You would write it like this to display other characters.
if((*p=='z') || (*p=='t') || ....)
4) see above answers.
Apart from the nice answer by Mr. #Lundin, just to clarify the logic for the print s,
1)why i got always an answer like "i got c".
Because, you wrote the code to do so. Keeping away the programmatic errors, if you check the logic, you wrote the code so that the printf() will only be executed if *p has a value equal to c. So, no wonder, all the time printf() (if encountered) will print
i got c
Next,
2) no matter how many times i execute this program, why i got %c as c.
Correct. Same reason as above.
3)replace c character with any character, no matter ,why we got such a character that what we put in if condition?.
Your printf() will only be executed if the if condition satisfies. So whatever character you'll use in your if condition, printf() will print only that character only.
You don't seem to know what you're doing.
Closest working exaple would look like this:
#include <stdio.h>
int main()
{
int a[2] = {0x0a0b0c0d, 0};
char *p = (char *) a;
while (*p)
{
if (*p == 0x0c)
{
printf("i got c\n");
return 0;
}
p++;
}
}
Or another better solution:
#include <stdio.h>
int main()
{
int a = 0x0a0b0c0d;
for (int i = 0; i < sizeof (int); i++)
{
if(((char *) &a)[i] == 0x0c)
{
printf("i got c\n");
return 0;
}
}
}

C pointer to character array

I would like to pass a character pointer ( to an array) to a function which will print the letters one by one. For example I am using the code below:
#include<stdio.h>
#include<string.h>
void string1(char *q)
{
while(*q)
{
printf(q++);
printf("\n");
}
}
main()
{
char name[]= "hello";
char *p=name;
string1(p);
}
which prints:
hello
ello
llo
lo
o
But I want it to print;
h
e
l
l
o
I am unable to do it by using the variable q inside printf. Thanks
Your sentence: printf(q++); is wrong.
You have to print a character, only:
printf("%c", *g++);
A better option:
putchar(*g++);
In general, take in account that:
g is the adress of an array of characters.
To access the first character pointed by g, it is necessary to use the operator *, this way: *g.
The modifier "%c" in printf() gives you the possibility of printing a datum of type char.
You should always use a format string with printf. Passing strings with unknown values into the printf function can result in an uncontrolled format string vulnerability. Printing a c-string with printf should be done like this: printf("%s", string_pointer);
That said, to print one character at a time you can use the %c formatter:
while(*q) {
printf("%c\n", *(q++));
}
You need to specify the first argument of printf()
By doing this:
printf(q++);
The application is behaving as if you want to print a string (because it keeps printing until it reaches \0), so what you are doing is equivalent to this;
printf("%s",q++);
But what you actually want is printing only the char at position q:
printf("%c",q++); // Prints only the char at q, then increment q

printing string in c using a pointer

I was just printing some characters in C.
I have declared char c and assigned its characters.
then using a for loop i try to print the characters one by one.
I have used pointers, of course.
#include <stdio.h>
#include <string.h>
int main()
{
char c[4] = {"hia"};
int i;
for(i=0;i<4;i++)
{
printf(&c[i]);
}
return 0;
}
However when I compile my code using turbo, i get output "hiaiaa" instead of "hia"! What am i doing wrong here?
Your printf() call is broken. You are using the string (from the point you specify) as the formatting string. This will not print single characters. Instead each call will print from where its formatting string starts, to end of the string.
This means the first call will print all of c, the next will print from c[1] and onwards, and so on. Not at all what you wanted.
If you want to print single characters, use the %c format specifier:
printf("%c", c[i]);
No pointer necessary, since the character is passed by value to printf().
This is what happened in your loop:
0. hia
1. ia
2. a
3. \0
However, you want to print exactly one char at a time, not a null terminated string, so you should pass it as char not a char*:
printf( "%c", c[i] )
Also, you are looping four times, but string length is just three. You should use:
for( i = 0; i < strlen( c ); i++ )
...
The printf function have an char* as first argument, that's correct. However, it prints a string (that is, a zero-terminated sequence of char) so it will always do that.
If you want to print one character at a time, then you have to use that format, like in:
printf("%c\n", c[i]);
You also have another problem, and that is that you try to print the zero terminator as well. This character is not printable so will not show. Use e.g. i < strlen(c) as the loop condition to overcome this.
Also, instead of printing character-by-character, print it all as one string:
printf("%s\n", c);
1) For loop size should i<3 , not i<4 (i=3 refers to the null character at the end of the string)
2) use printf("%c",c[i]);
Explanation of what you're seeing: In each loop, printf is printing a null-terminated string. This string starts in every loop one char later inside your array.
How it should be done, depends on what you're intending. If you want to print the string char by char via pointer you may use:
char *p=&c[0];
while (*p) {
printf("%c", *p);
p++;
}
Your question is to print string using pointer. You could use
printf("%s", c);
or character by character as (include library string.h for this)
for(i=0;i<strlen(c);i++)
{
printf("%c", c[i]);
}
in C strings are stored as character arrays and are terminated by a zero-value, so called zero-terminated strings. Btw, this is why you have to make the array size of 4 for thee real chars.
In your example, you are passing pointers th each char to the printf function and printf prints the strings from your pointer to the next null-value . The 1st pass prints "hia", the 2nd ia and the 3rd a.
To print a single char in each pass, you have to use
printf ("%c", c[i]);
Your loop will call printf with the following parameter:
printf("hia"); // first loop iteration
printf("ia"); // second loop iteration
printf("a"); // third loop iteration
printf(""); // fourth loop iteration
You probably meant to print one character at a time:
for(i=0;i<3;i++) // No need to print the string termination character.
{
printf("%c", c[i]); // "%c" is the printf format code to print a single character
}

* Vs ++ precedence in C

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 *

Resources