This question already has answers here:
Is printf()'s string width safe with unterminated strings?
(1 answer)
Undefined, unspecified and implementation-defined behavior
(9 answers)
Closed 5 months ago.
my question is I have created a char array of size 4.if i assigned values as below in the code without specifying the null character.How does it prints garbage values after the first four elements when the size of the char array is 4.
#include<stdio.h>
int main(){
char array[4];
array[0] = 'J';
array[1] = 'O';
array[2] = 'h';
array[3] = 'n';
printf("%s\n",array);
return 0;
}
You told printf() that you want it to print a string with %s but you passed it an array of chars. A string is an array of chars that is terminated by a '\0'. It may print garbage, as you found, or it that may crash the program (undefined behavior).
If you want to print an array of chars you want to use the format string %.4s in this case.
Related
This question already has answers here:
Does printf terminate every string with null character?
(3 answers)
What's the rationale for null terminated strings?
(20 answers)
Closed 24 days ago.
I would like to understand why this code works:
void open_image(const char *filename)
{
char *ImageName = filename;
printf("%s", ImageName);
}
const char image_name[] = "image.jpg";
open_image(image_name);
it prints "image.jpg" as wanted, but I don't know how the program knows the length of the string.
The program knows the size of the string image_name as it is computed during compilation.
But in the open_image function, how does the printf function knows the length of this string as it is only given the pointer ImageName created at runtime?
Thank you.
In C a string (array of char) is always terminated by the "terminator" character '\0', so you can get the length of the array by checking each character until you find it.
Here's a simple solution:
int i = 0;
char ch;
do
{
ch = arr[i];
i++;
} while(ch != '\0');
printf("String length: %d\n", i-1); // This will give the string length
printf("Total length of the array: %d\n", i); // This will give the array full length, including the terminator character.
Probably the best way to get a char array length is to import the string.h library which exposes the strlen() function.
However, it's always useful to learn how things actually work at low-level, especially when learning C). :-)
This question already has answers here:
How dangerous is it to access an array out of bounds?
(12 answers)
Undefined, unspecified and implementation-defined behavior
(9 answers)
Closed 3 months ago.
Why is it that the I seem not be able to use strcmp to compare two strings if I first create an array that just holds enough characters without the \0 character at the end and then put in the \0 at a later step like the following?
// The following from strcmp returns non-zero, so the two strings buff, t1 are
// not equal
char buff[4] = "K7Ag";
buff[4] = '\0';
char t1[5] = "K7Ag";
if(strcmp(buff, t1) == 0) {
printf("they are equal\n");
}
But if I do this:
// strcmp shows they are equal
char buff[5] = "K7Ag";
char t1[5] = "K7Ag";
if(strcmp(buff, t1) == 0) {
printf("they are equal\n");
}
I know I need a null character at the end of each string for strcmp to work properly. So why is it that I first create buff as:
char buff[4] = "K7Ag"
then append "\0" like:
buff[4] = '\0'
then call
strcmp(buff, t1) would not work?
Finally, can I assume that when I create a buff like
char b1[100] = "Abcd"
then I will have 96 null characters (i.e., 96 of those \0)
right after the character d in the b1 buffer?
So if I initialize a buffer with less than the allocated size, can I assume the rest of the buffer holds the \0 character?
This question already has answers here:
Passing not null terminated string to printf results in unexpected value
(6 answers)
Printing string using printf without null character [duplicate]
(1 answer)
how to make a not null-terminated c string?
(7 answers)
'\0' and printf() in C
(9 answers)
What are the repercussions of not using null termination in strings?
(3 answers)
Closed 8 months ago.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char s[40]="Who are you tell me that I can not code?";
char c=s[8];
char st[2];
st[0]=s[0],st[1]=s[1];
printf("%s \n",st);
return 0;
}
Why is it printing my original string 's' also when I'm printing st?
Output:-
WhWho are you tell me that I can not code?►
Process returned 0 (0x0) execution time : 0.048 s
Press any key to continue.
s is not a proper C string because it has exactly 40 bytes and 40 characters. C strings must have a null terminator byte. You should define it as:
char s[] = "Who are you tell me that I can not code?";
There is the same problem for st that you define as an array of 2 bytes where you store 2 characters. You should define st as an array of 3 bytes and set a '\0' null character at st[2].
Both of these problems can cause undefined behavior. and the second does as you pass st to printf() for a %s format which expects a proper C string pointer.
Here is a modified version:
#include <stdio.h>
int main() {
char s[] = "Who are you tell me that I can not code?";
char st[3];
st[0] = s[0];
st[1] = s[1];
st[2] = '\0';
printf("%s\n", st);
return 0;
}
Note that you can also print a substring with printf using the precision field:
#include <stdio.h>
int main() {
char s[] = "Who are you tell me that I can not code?";
// print the 3 characters at offset 4
printf("%.3s\n", st + 4);
return 0;
}
This question already has answers here:
How should character arrays be used as strings?
(4 answers)
Closed 1 year ago.
I'm trying to practice declaring Strings but I'm not getting correct output.
#include <stdio.h> //Im using vscode and gcc
int main()
{
char k[]= "prac c";
char l[6]= "stop c"; //first initializing as size 6
char m[6]= "nice c";
printf("%s \n%s \n%s",k,l,m);
return 0;
}
output: prac c
stop cprac c
nice cstop cprac c
But when I change the size from 6 to 7 this does not happen.
#include <stdio.h>
int main()
{
char k[]= "prac c";
char l[7]= "stop c"; //changing size to 7
char m[7]= "nice c"; //changing size to 7
printf("%s \n%s \n%s",k,l,m);
return 0;
}
output: prac c
stop c
nice c
The string "stop c" is really seven characters long, including the ending null-terminator. This goes for all your strings.
If there's no space in your arrays for the terminator then it won't be added, and the arrays are no longer what is commonly called strings.
Using such arrays as string will lead the code to go out of bounds of the arrays and give you undefined behavior.
"prac c", "stop c", "nice c" all occupy 7 bytes separately, as there's a terminating \0 for a string literal.
This question already has answers here:
How should character arrays be used as strings?
(4 answers)
Closed 3 years ago.
I want to write a C program that stores a bunch of sentences while it's running and prints them out at the end of the program.
Here's what I wrote:
#include<string.h>
#include<stdio.h>
int main(){
int counter = 0;
char state[100][200];
char stroo[3] = "yes";
sprintf(state[counter], "%s", stroo);
counter++;
char poo[2] = "44";
sprintf(state[counter], "%s", poo);
counter++;
for (int i=0; i<counter; i++) {
printf("%s\n", state[i]);
}
return 0;
}
For the output, the first line prints "yes" which is what I expected. The second line, however, prints "44yes". Why is it printing "yes" as well as "44"?
That's because your strings aren't correctly null-terminated, so you run into undefined behavior at the sprintf. This is because the buffer is too small to hold the null-terminator. For instance here:
char stroo[3] = "yes";
You need memory for four chars, the 'y', 'e', 's' and the null-terminator. Change it to
char stroo[4] = "yes";
Likewise char poo[2] needs to be char poo[3].
See here (emphasis mine):
Successive bytes of the string literal or wide characters of the wide string literal, including the terminating null byte/character, initialize the elements of the array [...] If the size of the array is known, it may be one less than the size of the string literal, in which case the terminating null character is ignored:
If you want the size to automatically be big enough to exactly fit the string, you can just leave out the size specification:
char stroo[] = "yes";
And of course, for this example, you don't even need to copy the string to the stack:
char *stroo = "yes";
#define STRINGS 5
#define STRING_SIZE 50
char arr[STRINGS][STRING_SIZE] =
{ "Hi",
"Hello world",
"Good morning",
"ASDF",
"QWERTY"
};
for (int i=0; i<STRINGS; i++) {
printf("%s\n", arr[i]);
}