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

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.

Related

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.

C chars add themselves up for no reason [duplicate]

This question already has answers here:
Space for Null character in c strings
(5 answers)
Closed 3 years ago.
I think I'm going insane because I cannot find an explanation to why C is combining my chars.
I've made you guys a test programm...
#include <stdio.h>
#include <stdlib.h>
int main()
{
char alphabet_big[26] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char alphabet_small[26] = "abcdefghijklmnopqrstuvwxyz";
printf("%s\n", alphabet_small);
return 0;
}
Results: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZV
Why is C combining alphabet_small and alphabet_big? That's not making sense. And why is there a "V" at the end of the char?
I hope someone can provide me an answer to this "problem".
Best regards.
Keep in mind that a C String is defined as a null terminated char array.
Change the declaration and initialization statement here: (for both statements.)
char alphabet_big[26] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//forces compiler to use only 26 char
//regardless of the count of initializers
//(leaving no room for NULL terminator)
To
char alphabet_big[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//allows compiler to set aside
^^ //the proper space, no matter how many initializers
The first produces undefined behavior when using with any of the string functions, such as strcpy, strcmp, and in this case printf with the "%s" format specifier.
The first produces the following, which is not is not a C string:
|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|?|?|?|
While the 2nd produces the following, which is a C string:
|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|\0|?|?|
Note - The ? symbols used in above illustration depict memory locations that are not owned by the program, and for which the contents are unknown, or may not even exist. A program attempting to access these locations would be invoking undefined behavior.
Normally the library functions expect to find a NUL byte at the end of a string, and the compiler is happy to add it for you automatically except you've told it that alphabet_big has only 26 bytes, essentially avoiding that extra NUL byte, so it combines with what's next.
Remove the 26 and let the compiler count for you.

comparing strings using equality sign in C programming [duplicate]

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 4 years ago.
#include<stdio.h>
int main()
{
char str1[] = "ComputerProgram";
char str2[] = "ComputerProgram";
(str1==str2)? (printf("Equal")):(printf("unequal"));
return 0;
}
The answer according to me should be equal but it comes out to be unequal.
However if I use strcmp(str1,str2) == 0 answer comes out to be equal. How is it working in == case.? Also, I tried to print the ASCII values of srt1 and str2, they came out to be different. So I think that might be the reason. Now the problem is how does == work for strings?
Your arrays str1 and str2 will decay to pointers to their first elements when you compare them. That is, you compare two pointers that will never be equal.
In short, your comparison str1 == str2 is equal to &str1[0] == &str2[0].
What strcmp does differently is that is compares each character in the first string against each corresponding character in the other string, in a loop.
str1==str2 is comparing the addresses of the strings, not the strings themselves.strcmp will go to these addresses and compare all characters.

explanation of the output of the following program [duplicate]

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)

Why does using the "%s" format specifier to printf an array of char output additional nonsense values after the final char in the array? [duplicate]

This question already has an answer here:
Is printf()'s string width safe with unterminated strings?
(1 answer)
Closed 5 years ago.
I stumbled upon this behavior that I am curious to understand.
I mistakenly wrote the following at the end of a program to print the elements in an array of char :
printf("output: %s",outputText[]);
when I should have (and ultimately did) iterate over the array and printed each element like so:
for(int i = 0; i < textLength; i++){
printf("%c",outputText[i]);
}
What prompted me to implement the latter was the output I was getting. Despite initializing the array to limit the characters to outputText[textLength], ensuring that there were no unexpected elements in the array, my output when implementing the former code would always be littered with additional spooky elements, like below:
I've just run the same program three times in a row and got three random characters appended to the end of my array.
(Edit to replace outputText[] --> outputText in first example.)
%s is for strings; a string is a array of chars ending with NUL (0x00 in hex, or '\0' as character), so the printf() will print until it finds a NUL!
If you set the last element of the array to NUL, printf will finish there.
You are probably missing the '\0' character as the element of the character array that marks the end of the string.
You are missing string terminating character \0 end of the string. So, make your string is \0 terminated. Like:
outputText[textLength-1] = '\0';

Resources