explanation of the output of the following program [duplicate] - c

This question already has answers here:
How is printf statement interpreted?
(5 answers)
Closed 5 years ago.
#include<stdio.h>
void main()
{
printf(5+"good morning");/*need explanation for this line
return 0;
}
The output of the program is - morning
can anyone explain how?

Prototype of printf
int printf(const char *format, ...);
Here format is a type of const char* and point to address of first element of string literal. When you pass 5+"Good morning" in printf, what you are really passing is the memory address of the string plus 5. The plus 5 means printing will start 5 chars beyond the start of the string, and the space after the word "Good",counts as a char.

when you call with 5+"good morning" parameter is converted to pointer. That means there is string constant "good morning" stored somewhere in the executable and compiler pass its pointer. something like this:
const char txt[]="good morning\0";
printf(5+txt);
So the printf will obtain the evaluated pointer txt+5 which bypassed first 5 characters in the string (as one char is single BYTE and single memory address on 8bit WORD addressing machines).

The output of the program is - morning
printf(5+"good morning");
prints the string inside the " ", overpassing the first five characters. So the first four characters g, o, o, d and the fifth character, the space, will be overpassed and the rest of the string will be printed.

Printf() method, is used to print the text in ()
It prints only "morning" and 5+ bypassed the initial 5 characters that is "g" "o" "o" "d" and a " " (space)

Related

C Arrays - Why is the last character in the array displaying, how do I get it to display only the first 5? [duplicate]

This question already has answers here:
How should character arrays be used as strings?
(4 answers)
Closed 2 months ago.
/* Variables */
int num;
char array[5]; // Array must also include NULL char
char new;
/* Accepting user input */
printf("Please enter 5 characters below:\n");
scanf("%c\r", &array[0]);
scanf("%c\r", &array[1]);
scanf("%c\r", &array[2]);
scanf("%c\r", &array[3]);
scanf("%c", &array[4]);
/* Displaying input as string */
printf("%s", array);
I am trying to create a basic program that creates a string that accepts chars one after the other. I know that arrays start at 0 and end with the null character so I made my array[5] so if I inputted "a" "b" "c" "d" "e" I would get the output string "abcde" plus the null character. Sometimes it works with one set of characters but not another. If I input "q" "w" "e" "r" "t" i might get the output "qwerta". How do I stop it from displaying that last character?
I understand that the reason why this character being displayed is that it is undefined and will show whatever value is at that memory location but I don't know how to fix it.
I have tried to include different escape sequences, putting spaces in the scanf and printf statements but what am I doing wrong?
You have a character array with size 5. You read a character into each of the five elements of the array. This does not leave space for the null character, and you do not explicitly set the last char equal to '\0'. Thus this is not a null terminated string, and printing it as a string with the %s specifier in printf has undefined behavior.

string without null terminator [duplicate]

This question already has answers here:
Undefined, unspecified and implementation-defined behavior
(9 answers)
Using printf with a non-null terminated string
(6 answers)
Closed 1 year ago.
#include <stdio.h>
int main()
{
char as[4];
*as='0';
*(as+1)='1';
*(as+2)='2';
*(as+3)='3';
printf("%s",as);
return 0;
}
The output i got is : 0123.
In the above program i declared an array of size 4 -> char as[4];
and in that i stored 4 chars 0,1,2,3.
Normally if we declare a char array, '\0' will be stored at last (i.e. as[3]='\0');
but i stored '3' in it. how it did not generate error?.
There is absolutely nothing stopping you from using an array of char as an array of char. There could be any number of reasons to want this.
However, C strings are null-terminated by definition. Using the %s specifier in printf tells it to expect a null-terminated string, so your program will (probably) not work correctly unless you give it such a string.

Why does printf() print two character arrays? [duplicate]

This question already has answers here:
Having difficulty printing strings
(5 answers)
Closed 3 years ago.
I have declared two simple character arrays.
When calling printf() on one string both arrays are printed.
Why?
#include <stdio.h>
int main()
{
char z[] = "The C programming language.";
char v[2] = {'q', 'w'};
printf("%s \n", v);
return 0;
}
Result expected: qw.
Result obtained: qwThe C programming language.
The two arrays are joined??
'q' is not the array only the integer.
When you initialize the array those two integers are stored as array elements.
Nothing is joined.
It is undefined behaviour as printf looks for the terminating zero and reads outside array bounds
In your example, z is a string, but v is a byte array.
The difference? z terminates with a \0 character, v does not.
Therefore it is OK to use printf() with %s to print a string, but you MUST use a for() (or something else similar) to print an array.

How to understand the statement of printf(str+9)? [duplicate]

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

Variable for Altering String Output in `printf()` - C Language [duplicate]

This question already has answers here:
Set variable text column width in printf
(2 answers)
Closed 6 years ago.
In C, as I understand so far, this would be correct:
printf("%10s\n", "This is C");
would return:
" This is C!"
(with the intentional space prior to the string; no quotations).
My question is can you replace the 10 specifying the length of the print using a variable? If so, how?
That's how:
printf("%*s\n", 10, "This is C");
The format changed from %10s to %*s. The printf() now would expect among the argument, before the string, an int with the width to pad the string to (the 10 in the example above; obviously could be a variable too).
To tell the printf() to pad the output to the left (instead of the default right) use the -: %-*s. (The output would change from " This is C" to "This is C ".)
To tell the printf() to take only few first bytes from the string, or if the string is not null-terminated, you can add .* to the format at the same place as the precision for floating point types. The printf() would print up to that number of characters, stopping at the first null character. Example:
int width = 10;
int chars = 4;
printf( "%-*.*s", width, chars, "This is C" );
would produce output "This ".

Resources