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.
Related
#include <stdio.h>
int main(int argc, const char *argv[]) {
char name1[] = {'f','o','o'};
char name2[] = "foo";
printf("%s\n", name1);
printf("%s\n", name2);
return 0;
}
running the code above results in :
foox\363\277\357\376
foo
Program ended with exit code: 0
So, what's the difference between these 2 initializers?
name1 is an array of three characters {'f', 'o', 'o'}.
name2 is an array of four characters {'f', 'o', 'o', '\0'}.
printf("%s", ...) expects an array terminated with a null character. Because name1 isn't, you start dereferencing characters past the end of the array which can have the traditional undefined behavior.
The first array (i.e., {'f','o','o'}) will not have the null character '\0', wheres the second (i.e., "foo") will.
The printf specification when using the %s says the following:
If no l modifier is present: The const char * argument is expected to
be a pointer to an array of character type (pointer to a string).
Characters from the array are written up to (but not including) a
terminating null byte ('\0'); if a precision is specified, no more
than the number specified are written. If a precision is given, no
null byte need be present; if the precision is not specified, or is
greater than the size of the array, the array must contain a
terminating null byte.
Since, your printf did not include the precision, it will write up characters from the array until reaching the null byte ('\0'). Consequently, in the case of the char name1[] = {'f','o','o'}; resulting in the printf write up characters out of the memory that was allocated for the name1 array. Such behaviour is considered to be undefined.
This is the reason why printf("%s\n", name1); prints foo plus some extra symbols from the next positions in memory that should not have been accessed, whereas with printf("%s\n", name2); it prints exactly the string "foo" as it is.
There are no trailing symbols in the array.
But printf’s %s format expects a string, and the array name1 isn’t a string: by definition, C strings are zero terminated … and your array isn’t. So the behaviour is undefined, and what seems to happen in your particular case is that printf continues printing random values that happen to be in memory just behind the contents of name1.
In C language if you are initializing string with character by character initializer you need to put '\0' which is NULL/terminating character to indicate the end of string.
so name1 should be {'f', 'o', 'o', '\0'}
x\363\277\357\376 that you can see at the end of your output is just garbage value which is printed just because printf could not find '\0' at the end of your string name1.
For name2 you used double quote to initialize the string which automatically puts a '\0' at the end of string.
In an introductory course of C, I have learned that while storing the strings are stored with null character \0 at the end of it. But what if I wanted to print a string, say printf("hello") although I've found that that it doesn't end with \0 by following statement
printf("%d", printf("hello"));
Output: 5
but this seem to be inconsistent, as far I know that variable like strings get stored in main memory and I guess while printing something it might also be stored in main memory, then why the difference?
The null byte marks the end of a string. It isn't counted in the length of the string and isn't printed when a string is printed with printf. Basically, the null byte tells functions that do string manipulation when to stop.
Where you will see a difference is if you create a char array initialized with a string. Using the sizeof operator will reflect the size of the array including the null byte. For example:
char str[] = "hello";
printf("len=%zu\n", strlen(str)); // prints 5
printf("size=%zu\n", sizeof(str)); // prints 6
printf returns the number of the characters printed. '\0' is not printed - it just signals that the are no more chars in this string. It is not counted towards the string length as well
int main()
{
char string[] = "hello";
printf("szieof(string) = %zu, strlen(string) = %zu\n", sizeof(string), strlen(string));
}
https://godbolt.org/z/wYn33e
sizeof(string) = 6, strlen(string) = 5
Your assumption is wrong. Your string indeed ends with a \0.
It contains of 5 characters h, e, l, l, o and the 0 character.
What the "inner" print() call outputs is the number of characters that were printed, and that's 5.
In C all literal strings are really arrays of characters, which include the null-terminator.
However, the null terminator is not counted in the length of a string (literal or not), and it's not printed. Printing stops when the null terminator is found.
All answers are really good but I would like to add another example to complete all these
#include <stdio.h>
int main()
{
char a_char_array[12] = "Hello world";
printf("%s", a_char_array);
printf("\n");
a_char_array[4] = 0; //0 is ASCII for null terminator
printf("%s", a_char_array);
printf("\n");
return 0;
}
For those don't want to try this on online gdb, the output is:
Hello world
Hell
https://linux.die.net/man/3/printf
Is this helpful to understand what escape terminator does? It's not a boundary for a char array or a string. It's the character that will say to the guy that parses -STOP, (print) parse until here.
PS: And if you parse and print it as a char array
for(i=0; i<12; i++)
{
printf("%c", a_char_array[i]);
}
printf("\n");
you get:
Hell world
where, the whitespace after double l, is the null terminator, however, parsing a char array, will just the char value of every byte. If you do another parse and print the int value of each byte ("%d%,char_array[i]), you'll see that (you get the ASCII code- int representation) the whitespace has a value of 0.
In C function printf() returns the number of character printed, \0 is a null terminator which is used to indicate the end of string in c language and there is no built in string type as of c++, however your array size needs to be a least greater than the number of char you want to store.
Here is the ref: cpp ref printf()
But what if I wanted to print a string, say printf("hello") although
I've found that that it doesn't end with \0 by following statement
printf("%d", printf("hello"));
Output: 5
You are wrong. This statement does not confirm that the string literal "hello" does not end with the terminating zero character '\0'. This statement confirmed that the function printf outputs elements of a string until the terminating zero character is encountered.
When you are using a string literal as in the statement above then the compiler
creates a character array with the static storage duration that contains elements of the string literal.
So in fact this expression
printf("hello")
is processed by the compiler something like the following
static char string_literal_hello[] = { 'h', 'e', 'l', 'l', 'o', '\0' };
printf( string_literal_hello );
Th action of the function printf in this you can imagine the following way
int printf( const char *string_literal )
{
int result = 0;
for ( ; *string_literal != '\0'; ++string_literal )
{
putchar( *string_literal );
++result;
}
return result;
}
To get the number of characters stored in the string literal "hello" you can run the following program
#include <stdio.h>
int main(void)
{
char literal[] = "hello";
printf( "The size of the literal \"%s\" is %zu\n", literal, sizeof( literal ) );
return 0;
}
The program output is
The size of the literal "hello" is 6
You have to clear your concept first..
As it will be cleared when you deal with array, The print command you are using its just counting the characters that are placed within paranthesis. Its necessary in array string that it will end with \0
A string is a vector of characters. Contains the sequence of characters that form the
string, followed by the special ending character
string: '\ 0'
Example:
char str[10] = {'H', 'e', 'l', 'l', 'o', '\0'};
Example: the following character vector is not one string because it doesn't end with '\ 0'
char str[2] = {'h', 'e'};
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.
In my program, I am making a char line[MAXLINE] and then using it in:
fgets(line, sizeof line, f);
I can then print this line with
printf("%s\n",line);
However, trying something like
printf("%s\n",line[10]);
warns me that line[10] is of type int, and something like
printf("%s\n",line + 10);
prints from character 10 onwards.
how can I just get the nth character of this string?
You can get the nth character like so:
char ch = line[10];
But you can't print it as a string, because it's not a string. Print it as a character:
printf("%c\n", line[10]);
What you are doing when you use %s in the format string in printf is printing the null-terminated string starting from the the provided pointer.
line+10 is the pointer to the 11th character in the string so it prints everything it finds in memory until it encounters /0 (null) character.
To print a single character you have to use %c in the format string.
printf("%c",line+10);
printf("%s\n",line + 10); // %s expects a char *
Instead print like this -
printf("%c\n",line + 10);
how can I just get the nth character of this string?
With strlen() function from <string.h> you can get length of string. Thus easily you can get the nth character. of the string.
The below will also work as a string in C is a char pointer to the first character. (Strings are terminated in memory with the character \0, that's how programs know where they end.)
line is a pointer to the first character and it can be advanced to the 10th character, as below (we have to advance it by 9, as no advance points to the first character).
* dereferences the pointer to get the actual value.
#include <stdio.h>
int main()
{
char line[] = "abcdefghijkl";
printf("%c\n", *(line+9));
return 0;
}
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;
}