string without null terminator [duplicate] - arrays

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.

Related

Why string[10] containing more 10 character in c? [duplicate]

This question already has answers here:
Char array can hold more than expected
(3 answers)
Why is the gets function so dangerous that it should not be used?
(13 answers)
Closed 28 days ago.
I'm taking array of character size of 10 , but in return it gives me out-range array(10+) string, YOU CAN REFER TO MY CODE
#include<stdio.h>
int main(){
char name[10]; `array of 10 Character`
gets(name); `INPUT: THIS IS BEAUTIFUL WORLD!`
printf("Given string %s", name); `it should print only 10 string in c`
` OUTPUT : Given string THIS IS BEAUTIFUL WORLD! `
return 0;
}
https://en.cppreference.com/w/c/io/gets
char *gets( char *str );
The gets() function does not perform bounds checking, therefore this function is extremely vulnerable to buffer-overflow attacks. It cannot be used safely (unless the program runs in an environment which restricts what can appear on stdin). For this reason, the function has been deprecated in the third corrigendum to the C99 standard and removed altogether in the C11 standard. fgets() and gets_s() are the recommended replacements.

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.

How to convert integer to char array[]? [duplicate]

This question already has answers here:
How can I convert an int to a string in C?
(10 answers)
Closed 3 years ago.
Please read till the end.
I have a function that loops through a character array until it finds the '\0' end character in a character array.
I want to convert the integer
int number = 128;
To a character array
char data[] = ""; // data[] = "128" , contains '\0'
I have found several ways suggested (memcpy, itoa) but I want a conversion that adds the '\0' automatically at the end.
itoa() automatically adds a null terminator.
See: http://www.cplusplus.com/reference/cstdlib/itoa/

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

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.

Sprintf function + order arguments [duplicate]

This question already has answers here:
Can the input and output strings to sprintf() be the same?
(2 answers)
Closed 7 years ago.
I have two string ta and tb with certain value, then I use the function sprintf to concatenate the two both in the variable ta, when I write
sprintf(ta,"%s+%s",ta,tb);
I get the string 1+2. but I need store in ta the string 2+1 then I trying
sprintf(ta,"%s+%s",tb,ta);
but I get the string 2+2+2+2+. I don't understand why happens that, Could you help me please?. Below the complete code
int main() {
char ta[5];
char tb[5];
sprintf(ta,"%d",1);
sprintf(tb,"%d",2);
sprintf(ta,"%s+%s",ta,tb);
//sprintf(ta,"%s+%s",tb,ta); uncomment for the second case
printf("taid:%s",ta);
}
sprintf(ta,"%s+%s",ta,tb);
sprintf(ta,"%s+%s",tb,ta);
Both lines of calling sprintf have undefined behavior. You are trying to copy ta to ta itself.
C11 ยง7.21.6.6 The sprintf function
The sprintf function is equivalent to fprintf, except that the output is written into an array (specified by the argument s) rather than to a stream. A null character is written at the end of the characters written; it is not counted as part of the returned value. If copying takes place between objects that overlap, the behavior is undefined.

Resources