Printing array of characters using printf - c

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!

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";

K&R How is the char array being reset?

In K&R, we are introduced to char arrays to represent strings.
Arrays are passed by reference. From what I understand, we can point to the first element in an array (pointer?). Using the char array input without really defining its values means it sets garbage data inside the array. (Honestly not really sure what garbage data is, maybe nulls?).
Anyways, initially the empty char array is passed to function getLength, and it sets char array inputs. In my code, I display the len and char array input.
On the next input, I call getLength again, and pass the same char array input. I set the values like before and return the length.
How is the old input erased? Aren't I referencing the exact same array that previously stored the previous input? Below my code, I'll show an example.
#include <stdio.h>
#define MAXLINE 1000 /* For allocating storage size for char array */
int getLength(char s[]); /* set char array and return length */
int main(void) {
int len;
char input[MAXLINE];
while ((len = getLength(input)) > 0) {
printf("len = %d\n", len);
printf("string = %s", input);
}
}
int getLength(char s[]) {
int i, c;
for (i = 0; i < MAXLINE - 1 && (c = getchar()) != EOF && c != '\n'; ++i) {
s[i] = c;
}
if (c == '\n') {
s[i++] = '\n';
}
s[i] = '\0';
return i; /* return length including newline */
}
Example:
Input: "Hello my name is Philip"
Output: "len = 24"
"string = Hello my name is Philip"
Input: "Hi"
Output: "len = 3"
"string = Hi"
When I input "Hi", aren't I using the previous array that has "Hello my name is Philip" stored inside. So won't I expect the array to look like:
['H', 'i', '\n', '\0', 'o', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'P', 'h', 'i', 'l', 'i', 'p', '\n', '\0', etc...]
Edit:
Just to clarify, I understand how printf("%s", input) is printing the correct string. I also understand getLength will return the correct length every time.
I'm just confused about the chars saved in the array input. If we are referencing this same array in memory, how are old chars being handled?
How is the old input erased? Aren't I referencing the exact same array
that previously stored the previous input?
The old input is not erased. In each iteration of the loop, you are just overwriting the same array input and is freshly zero terminated (s[i] = '\0';) by getLength() in each iteration.
Since you are printing the string before the next iteration, it makes it possible to reuse the same array (and overwrite it). So, there really isn't any need to "save" anything.
C arrays are pointers to memory. With the line char input[MAXLINE]; you have allocated a contiguous block of 1000 bytes. Which are not going to be initialized every time unless you do so explicitly. The junk data you refer to is simply the previous iterations of using this block of bytes.
The end of a char array as a string is usually indicated by the '\0' character. Libraries that use string i/o like stdio.h make this assumption and calculate length by traversing the string until the zero character is encountered. One possible danger exists when you write nonzero characters all the way to the end of your array and then use strlen from stdio.h to find the length of your string. The function will go beyond the end of the buffer and crash your program.

character array printing output

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;
}

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