Code snippet
int main(){
printf(5 + "GeeksQuiz");
return 0;
}
Output is Quiz
Can you tell me how this output is coming.
Whats the logic behind it.
Addition is commutative. a + b is equal to b + a.
Adding an integer to a pointer increments follows pointer arithmetic. Adding an integer to a pointer increments it by so many elements as the integer count. So (int*)a + b is equal to (int*)((uintptr_t)a + b * sizeof(int))
sizeof(char) is always equal to 1.
"GeeksQuiz" is a string literal. strlen("GeeksQuiz") is equal 9. Accounting for the string terminating null byte, the type of the literal is char[10]. It's an array of 10 characters with the content {'G','e','e','k','s','Q','u','i','z','\0'}.
The C rules say, that an array of type is converted into a pointer to the first element of that array in most contexts. That happens here: (char[])"GeeksQuiz" is converted into a char* pointer to the first character 'G' in the string.
5 + "GeeksQuiz": "GeeksQuiz" is converted to the pointer to the first character. Then that pointer is incremented by 5. So the result of 5 + "GeeksQuiz" will be char* pointer that will point to the character 'Q' inside the string literal.
printf prints the null terminated string passed to it as the first character, except for conversions that start with %, which does not apply here.
To the printf function is passed the address of a pointer that points to the letter 'Q' inside the "GeeksQuiz" string literal.
printf increments the pointer until it will find the string terminating null byte. So it will print {'Q','u','i','z'}, as after z character it will find the null byte.
Related
I have been studying the C language for the last few months. I'm using a book and I have this exercise:
char vector[N_STRINGS][20] = {"ola", "antonio", "susana"};
char (*ptr)[20] = vector;
char *p;
while(ptr-vector<N_STRINGS)
{
p = *ptr;
while(*p)
putchar(*p++);
putchar('\n');
ptr++;
}
I understand everything expect the while(*p)! I can't figure out what the while(*p) is doing.
The variable p in your code is defined as a pointer to a char. The get the actual char value that p points to, you need to dereference the pointer, using the * operator.
So, the expression in your while loop, *p evaluates - at the beginning of each loop - to the char variable that p is currently pointing to. Inside the loop, the putchar call also uses this dereference operator but then increments the pointer's value so, after sending that character to the output, the pointer is incremented (the ++ operator) and it then points to the next character in the string.
Conventionally (in fact, virtually always), character strings in C are NUL-terminated, meaning that the end of the string is signalled by having a character with the value of zero at the end of the string.
When the while loop in your code reaches this NUL terminator, the value of the expression *p will thus be ZERO. And, as ZERO is equivalent to a logical "false" in C (any non-zero value is considered "true"), the while loop will end.
Feel free to ask for further clarification and/or explanation.
From the C Standard (6.8.5 Iteration statements)
4 An iteration statement causes a statement called the loop body to be
executed repeatedly until the controlling expression compares equal to
0.
In this part of the program
p = *ptr;
while(*p)
//…
the pointer p points to the first character of a current string. String in C is a sequence of characters terminated by the zero character '\0'.
So let's for example the pointer initially points to the first character of the string "ola". The string is represented in the corresponding character array like
{ 'o', 'l', 'a', '\0' }
The condition in the loop
while(*p)
may be rewritten like
while(*p != 0 )
So the loop will be executed for all characters of the string except the last zero-terminated character and there will be outputted the first three characters of the string.
Pay attention to that (6.5.9 Equality operators)
3 The == (equal to) and != (not equal to) operators are analogous to
the relational operators except for their lower precedence.108) Each
of the operators yields 1 if the specified relation is true and 0 if it
is false. The result has type int. For any pair of operands, exactly
one of the relations is true.
This question already has answers here:
Pointer Arithmetic [closed]
(7 answers)
Closed 5 years ago.
#include<stdio.h>
void main()
{
char *str="CQUESTIONBANK";
clrscr();
printf(str+9);
getch();
}
The output is BANK. what the printf statement does. Can anyone please explain that?
A string in C is defined as a sequence of char terminated by a '\0'. A string isn't a type in C. So, functions handling strings accept a pointer to the beginning of the string (a pointer to char).
You can do arithmetics on pointers. + x means increase the pointer by x elements pointed to. So, str+9 in your example points to the character B. This pointer is passed as the start of the string to printf().
str gives the base address of the pointer to the string.
So normally if you just use printf(str) it should output CQUESTIONBANK.
But in this case you are printing str+9, ie. printf(str+9), so in this case it refers to string starting from the 9th index. In this case the 9th index is B,(C follows 0 indexing), so the string printed is BANK.
printf will always print the string from the passed pointer as starting position till the end of the string, which is stored as '\0' known as Null Character. If you try printf(str[13]), it should print '\0'
#include<stdio.h>
void main()
{
char *str="CQUESTIONBANK";
/* clrscr() function will clear the console.*/
clrscr();
/* printf() function, outputs the data. The name of the string, in your case
it is 'str' always points first element of the string which is 'C'. Adding 9 will
'str' point to 'B' character in the string. That's why printf is printing from B on wards.
Similarly adding 10 to 'str' will print from 'A' and so on.*/
printf(str+9);
/* getch() function waits for you to enter any character.*/
getch();
}
str points to a location (address). You can move in any direction over these addresses using + and -. So, if str points to some address, say 0x1002, then str+1 points to 0x1003 and str-1 points to 0x1001. (assuming str is char*. With other pointer types you move in bigger steps - sizeof(*str))
In your example - str points to an address that holds CQUESTIONBANK so if you move the pointer 9 steps forward, you move past C,Q,U,E,S,T,I,O,N and you now point to BANK. Now using printf will print from that location resulting in BANK
#include<stdio.h>
int main()
{
char *p;
p="%d\n";
p++;
p++;
printf(p-2, 400);
return 0;
}
When I am running above code, I am getting output 400. But why 400?
The p is assigned the formatting string first. Then it's decrement by 1 two times. Finally its value minus two is passed to the printf with additional parameter 400.
Subtracting 2 from latest value of p moves it back to the original formatting string. And therefore printf prints value 400.
printf()'s first parameter is a format string. The variable p is a pointer to a character array which is also how strings are represented.
When p is assigned a string "%d\n" it says format an integer to print its value and then print the carriage return character.
Since p is a char pointer p++ means move the pointer forward 1 character. This is done twice to move p forward 2 characters so it points to the beginning of the carriage return character. p-2 says do pointer math to give a char* 2 characters in front of where p points.
This is the beginning of the %d carriage return string. This becomes the format string and the second parameter 400 replaces the %d and prints itself followed by the carriage return.
You declared a pointer to a string and assigned it the value "%d\n". This pointer holds an address in memory.
For example, lets say it points to address 6 when you add two to it (which you shouldn't do you you always have to know where your pointers are pointing) you change the address to 8.
Now when you do printf you're replacing it with the current value of the address p points to (8) minus 2 which is 6.
int main(){
printf("the value is %d \n " ,'x'+ "x");
return 0;
}
Output
4196024
But the former one ('x') is an integer and latter one ("x")is a string .
Can I know how ? Or is it giving me a garbage value.
Literal strings have type char [N] where N is just large enough for all characters in the literal plus the terminating '\0' (namely "x" has type char[2]).
In the context of the expression 'x' + "X", the array gets converted to a pointer to its first element, then that address is added with the int value 'x'. The resulting address is passed on to printf() with an invalid conversion specification.
You have invoked Undefined Behaviour!
Try this
printf("the valus is %p\n", (void*)('x' + "x"));
Also note that the address 'x' + "x" is not part of any object in your program. Merely evaluating it is already Undefined Behaviour.
Basically,
printf("the value is %d \n " ,'x'+ "x");
invokes undefined behaviour. What you need is %p format specifier here.
Otherwise, in general,
"string" gives you the base address of the string literal
'p' gives you the ASCII value of the char representation.
So, what essentially is being done here is to print the address of the member in 'x'th element of the string "x" (which does not make much sense, practically).
For better understanding, you can re-write the print statement as
printf("the pointer is %p\n", (void *) ("x"+ 'x'));
which is equivalent to
printf("the pointer is %p\n", (void *) &("x"['x']));
Note that you don't need spaces before or after the newline in the print format.
What you are asking for in the formatted string is an integer so it is printing the integer value of the character 'x' added to the base address of the string literal "x".
'x' is 120 so if you use a memory viewer to peek at the outputted value minus 120 bytes, you will probably find an 'x' followed by a '\0' (= 0).
#include <stdio.h>
#include <string.h>
main()
{
printf("%d \n ",sizeof(' '));
printf("%d ",sizeof(""));
}
output:
4
1
Why o/p is coming 4 for 1st printf and moreover if i am giving it as '' it is showing error as error: empty character constant but for double quote blank i.e. without any space is fine no error?
The ' ' is example of integer character constant, which has type int (it's not converted, it has such type). Second is "" character literal, which contains only one character i.e. null character and since sizeof(char) is guaranteed to be 1, the size of whole array is 1 as well.
' ' is converted to an integer character constant(hence 4 bytes on your machine), "" is empty character array, which is still 1 byte('\0') terminated.
Here in below check the difference
#include<stdio.h>
int main()
{
char a= 'b';
printf("%d %d %d", sizeof(a),sizeof('b'), sizeof("a"));
return 0;
}
here a is defined as character whose data type size is 1 byte.
But 'b' is character constant. A character constant is an integer,The value of a character constant is the numeric value of the character in the machine's character set. sizeof char constant is nothing but int which is 4 byte
this is string literals "a" ---> array character whose size is number of character + \0 (NULL). Here its 2
This is answered in Size of character ('a') in C/C++
In C, the type of a character constant like 'a' is actually an int, with size of 4 (or some other implementation-dependent value). In C++, the type is char, with size of 1. This is one of many small differences between the two languages.
The 'space', or 'any single character', is actually of type integer, equal to the ASCII value of that character. So it's size will be 4 bytes.
If you create a character variable and store a character in it, then only it is stored in 1 byte memory.
char ch;
ch=' ';
printf("%d",sizeof(ch));
//outputs 1
For anything to be a string, it must be terminated with a null character represented as '\0'.
If we write a string "hello", it is actually stored as 'h' 'e' 'l' 'l' 'o' '\0', so that the system knows string ends after the 'o' in "hello" and it stops reading when null character comes. The length of this string is still 5 if you use strlen() function but actually the sizeof(string) is 6 bytes.
When we create an empty string, like "", it's length is 0 but size is 1 byte as it must terminate where it starts, i.e. at 0th character.
Hence an empty string consists of only one character, that is null character, giving size 1 byte.
From C Traps and Pitfalls
Single and double quotes mean very different things in C.
A Character enclosed in single quotes is just a another way of writing the integer that corresponds to the given character in ASCII implementation. Thus ' ' means exactly same thing as 32.
On the other hand, A string enclosed in double quotes is a short-hand way of writing a pointer to the initial character of a nameless array that has been initialized with the characters between the quotes and an extra character whose binary value is zero. Thus writing "" that is empty string still has '\0' character whose size is one.
because of in 1st case there is a character that's why sizeof operator is take the SACII value of character and it's take as an integer so in 1st case it will give you 4.
in 2nd case sizeof operator take as a string and in string there is no data means it's understood NULL string , so NULL string size is 1, that's why it will give you answer as a 1.