Sprintf function + order arguments [duplicate] - c

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.

Related

string without null terminator [duplicate]

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.

Why doesn't a string called by a function equal the string held in a command argument vector even though they ar the same [duplicate]

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
How to properly compare command-line arguments?
(4 answers)
How to compare string command line arguments in C?
(6 answers)
Don't know how to check input arguments in C
(1 answer)
How are filenames stored when they're passed as command line arguments in C?
(1 answer)
Closed 1 year ago.
My code reads as below:
if (array[i].name == name)
Array.name is assigned by an argc, then name is entered by the user. I've used a debugger to check the values, and prior to hitting this if command, array[i].name = Joe and name = Joe.
But the if function doesn't run... I'm lost. Everything I can see is showing that these two strings hold the same word, so why won't the if command recognize that?
You can't compare strings in C like that.
As Paul Rooney said in the comment,
You need a function to iterate through the strings and compare them
char by char.
So you can either create your own function that iterates through the strings and compares them char by char or you can use strcmp() to compare the strings. Here's how to compare the strings using strcmp():
if(strcmp(array[i].name,name)==0){
//do something if the strings are equal
}
Note:
strcmp() returns an integer indicating the result of the comparison,
as follows:
• 0, if the s1 and s2 are equal;
• a negative value if s1 is less than s2;
• a positive value if s1 is greater than s2.

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.

What happens in C if you don't use \0 at the end of a string? [duplicate]

This question already has answers here:
What happened when we do not include '\0' at the end of string in C?
(5 answers)
Closed 4 years ago.
so I know that in C, that '\0' is the null character, used to terminate strings. I've been looking online to see what it actually does, and I've run programs with and without it in my strings to see the difference in its use and non-use. I can't find any.
What can I not do when my strings lack the '\0' character?
Code that worked for me without a \0:
char a[10] = {'a','b','c','d','e','f','g'};
int x = strlen(a);
char b[10] = {'h','i','j','k','l'};
int y = strcmp(a,b);
printf("%d\n",x);
printf("%d\n",y);
According to the standard (C11 §7.1.1), if it doesn't end with a null byte it is not technically a 'string', it is simply a char array. (Make no mistake c-strings are char arrays as well, but they end in a terminator.)
You won't be able to use many of the string functions strcat, strcmp, strcpy, strlen, printf, etc, without a lot of your own built-in safeguards. Note, you can perform similar operations if you keep track of the length of the string manually and use functions like memcpy, strnlen, sprintf, etc, but you aren't technically working with c-string when doing so, you're simply working with arrays.

Are scanf arguments allowed to alias? [duplicate]

This question already has answers here:
Is scanf("%d%d", &x, &x) well defined?
(3 answers)
Closed 6 years ago.
I'm using scanf to extract very regular tabular data. I need to go over it in two passes and can safely ignore some of the arguments some of the time.
I want to allocate space for only the strings I care about and a single "discard" string for the others. If I pass this argument multiple times as output, is the behavior defined?
A silly minimal example:
char label[MAX_SIZE], discard[MAX_SIZE];
sscanf(input, "%s %s %s %s", discard, label, discard, discard);
I cannot find any language in the C11 standard that makes your intended usage invalid.
There seems to be a better solution, though. If you place a * (“assignment suppression character”) after the % in the format string, then the scanf function will parse but not store the input item. Hence, you don't have to (must not, actually) provide a destination argument for it. Seems to be exactly what you need here.
If I pass this argument multiple times as output, is the behaviour defined?
Citing C11:
7.21.6.2 The fscanf function
int fscanf(FILE * restrict stream,
const char * restrict format, ...);
The fscanf function executes each directive of the format in turn. When all directives have been executed, or if a directive fails (as detailed below), the function returns.
The fscanf function (and therefore sscanf) executes each directive of the format in turn, therefore there should be no problems assigning to discard parameters multiple times, as the final assignment would have the final effect (overwriting the previous assignments).

Resources