character array printing output - c

I am trying to understand outputs of printing character arrays and it is giving me variable outputs on ideone.com(C++ 4.3.2) and on my machine (Dev c++, MinGW compiler)
1)
#include<stdio.h>
main()
{
char a[] = {'s','t','a','c','k','o'};
printf("%s ",a);
}
It prints "stacko" on my machine BUT doesn't print anything on ideone
2)
#include<stdio.h>
main()
{
char a[] = {'s','t','a','c','k','o','v','e'};
printf("%s ",a);
}
on ideone : it prints "stackove" only the first time then prints nothing the subsequent times when i run this program
on my dev-c : it prints "stackove.;||w"
what should be the IDEAL OUTPUT when I try to print this kind of character array without any '\0' at the end , it seems to give variable outputs everywhere . please help !

%s conversion specifier expects a string. A string is a character array containing a terminating null character '\0' which marks the end of the string. Therefore, your program as such invokes undefined behaviour because printf overruns the array accessing memory out of the bound of the array looking for the terminating null byte which is not there.
What you need is
#include <stdio.h>
int main(void)
{
char a[] = {'s', 't', 'a', 'c', 'k', 'o', 'v', 'e', '\0'};
// ^
// include the terminating null character to make the array a string
// output a newline to immediately print on the screen as
// stdout is line-buffered by default
printf("%s\n", a);
return 0;
}
You can also initialize your array with a string literal as
#include <stdio.h>
int main(void)
{
char a[] = "stackove"; // initialize with the string literal
// equivalent to
// char a[] = {'s', 't', 'a', 'c', 'k', 'o', 'v', 'e', '\0'};
// output a newline to immediately print on the screen as
// stdout is line-buffered by default
printf("%s\n", a);
return 0;
}

Related

why the size of string is same as number of char but length is one more than number of char?

I used the following code:
#include <stdio.h>
#include <string.h>
void main()
{
char c[] = {'J', 'O', 'H', 'N'};
printf("size (bytes)=%d\n", sizeof(c));
int len = strlen(c);
printf("Length = %d\n", strlen(c));
printf("%s", c);
The output size of the string is 4, but the length is 5. is the string not supposed to have /0 at the end? So the output size of the string should be 5, but the length is 4.
If I write code as char c[] = {'J', 'O', 'H', 'N', \0}; or c[] = "JOHN" then I got output size of the string is 5, the length is 4
In C, a string is a sequence of character values including a 0-valued terminator - the string "JOHN" would be represented as the sequence {'J', 'O', 'H', 'N', 0 }.
Strings are stored in arrays of character type - because the you need to store the terminator in addition to the characters of the string, the size of the array has to be at least one more than the length of the string. IOW, to store the 4-character string "JOHN" you need an array that's at least 5 elements wide.
Had you initialized the array as
char c[] = "JOHN";
then the terminator would have properly been accounted for.
If the terminator isn't present, then what you have isn't a string and the various str* library functions won't handle it properly. In your case above, strlen looked through the elements {'J', 'O', 'H', 'N'} and didn't find the 0 terminator, so it kept looking past the end of the array until it saw a zero-valued byte.
The definition of a string in C is that it is an array of characters, terminated by a null character, or '\0'.
You wrote:
char c[] = {'J', 'O', 'H', 'N'};
So let's see.
array of char: ✅
terminated by a null character: ❌
So c is not a string. So it's not valid to call strlen on it, and it's not valid to print it out using printf's %s format.
You could make it a proper string by changing the initialization to:
char c[] = {'J', 'O', 'H', 'N', 0};
or equivalently
char c[] = {'J', 'O', 'H', 'N', '\0'};
Or it would be easier and clearer to just write
char c[] = "JOHN";
When you use a string literal (that is, a string in double quotes) as an initializer for a character array like that, the compiler automatically does exactly the same thing for you as if you had written {'J', 'O', 'H', 'N', '\0'};, but it's obviously a lot less typing.

why the result of strlen() out of my expection?

The function strlen() counts the number of characters in a string up to NUL and it doesn't contain
NUL.In ASCII,NUl is equal to '\0'.
#include<stdio.h>
#include<string.h>
int main(void)
{
char a[]="abc";
char b[]="abcd'\0'def";
printf("%d\n%d",strlen(a),strlen(b));
return 0;
}
The result is 3 and 5.
THe second result is in contradiction with the first result.
Thus ,I try to find how to implement strlen().
int strlen(char a[])
{
int i;
for(i=0;a[i]!='\0';i++);
return i;
}
Based on this code ,I can understand the first result,but really can't understand the second one.
Why is the sceond result not 4 but 5?Thanks in advance.
You are getting 5 because you have wrapped the NUL character in single quotes, the value 5 is the length of the string "abcd'".
If you change the second example to "abcd\0ef" (no single quotes), you get a value of 4.
char b[]="abcd'\0'def";
the array elements are
[a][b][c][d]['][0]['][d][e][f][0]
so the lenthth of the string before first [0] is 5 as it contains ' character as well.
In ASCII, NUL is equal to '\0'.
NUL, and the null character, are equal to '\0', that is correct. But what you are looking here is a character literal (one character, \0, enclosed in single quotes). Within a string literal, those single quotes are not needed, and will indeed be interpreted as characters of their own.
So this...
char a[]="abc";
char b[]="abcd'\0'def";
...is equivalent to:
char a[]= { 'a', 'b', 'c', '\0' };
char b[]= { 'a', 'b', 'c', 'd', '\'', '\0', '\'', 'd', 'e', 'f', '\0' };
Your intention for b was this:
char b[]="abcd\0def";

Does printf terminate every string with null character?

We have a statement like-
printf("Hello World");
Does printf append a null character after 'd' in the given string?
When you write
printf("xyz");
you are actually passing a string consisting of three characters and a null-terminator to printf.
printf("xyz");
// is equivalent to
static const char xyz[] = { 'x', 'y', 'z', 0 };
printf(xyz);
both printfs have the same effect: they write the characters x, y and z to the console. The null-terminator is not written.
Try this:
#include <stdio.h>
int main()
{
char string0[] = {'a', 'b', 'c'};
char string1[] = {'a', 'b', 'c','\0'};
printf("%s", string0);
puts("");
printf("%s", string1);
return 0;
}
If you are lucky enough, you will see something like:
abc$#r4%&^3
abc
printf() does not append a '\0' to the string. It doesn't make any change to the string to be output, because its task is to "print", rather than "modify". Instead, it is the null characters that tell printf() where is the end of the strings.
When a string is defined e.g. "hello world" it is null terminated by default. printf does nothing related to null terminate expect its own print processing. It only accepts char* as input. In your example "Hello World" is temp string and null terminated already before passed to printf. If the passed string is not null terminated then the behavior is undefined.

Printing array of characters using printf

Is there a way I can print an array of characters using 'printf' in the following way (I know this isn't correct C code, I want to know if there is an alternative that will yield the same result).
printf("%s", {'h', 'e', 'l', 'l', 'o' });
This will work, but the length of the array must either be hard-coded in the format string or as a parameter or else the array must be defined twice (perhaps by one macro) so that its size can be calculated by the compiler:
printf("%.5s", (char []) {'h', 'e', 'l', 'l', 'o' });
How about a simple while loop? Assuming the array is null-terminated, of course. If not - you'll need to adjust to counting the number of characters in the array.
char a[] = {'h','e','l','l','o','\0'};
int i = 0;
while (a[i] != "\0")
{
printf ("%c,", a[i]);
i++;
}
Output:
h,e,l,l,o,
Note: do NOT try this on a char**! This is for char[] only!

Error printing out an element in an array

I'm trying to print out an element in my array:
#include <stdio.h>
int main(void) {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("%s", greeting[0]);
return 0;
}
I expect it to print out H, but instead it crashed and the Windows dialog popped up:
"program.exe has stopped working"
What did I do wrong?
Try printf("%s", &greeting[1]); it should print "ello":
1) "greeting" is a character array containing the string "Hello\0".
2) You can call printf("%s\n", greeting); with no problem.
3) "greeting[0]" is the first character in the array.
"&greeting[0]" is a pointer to the first character in the array.
printf("%s", s) expects s to be a pointer, not a character.
4) Alternatively, you might want to print just a character.
In this case, try printf("%c", greeting[0]);
5) Use "%s" to print a string, use "c%" to print a character. Use "%d" or "0x%02x"to print the ASCII representation of the character.
'Hope that helps
You should write
printf("%c", greeting[1]);
to write out a single character ('H') instead of trying to print a string. Your program crashes because %s expects a char* parameter to be passed, but greeting[1] is of type char.
You should do:
printf("%c \n", greeting[1]);
The format specifier to print a char is c. So the format string to be used is %c.

Resources