comparing strings using equality sign in C programming [duplicate] - c

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 4 years ago.
#include<stdio.h>
int main()
{
char str1[] = "ComputerProgram";
char str2[] = "ComputerProgram";
(str1==str2)? (printf("Equal")):(printf("unequal"));
return 0;
}
The answer according to me should be equal but it comes out to be unequal.
However if I use strcmp(str1,str2) == 0 answer comes out to be equal. How is it working in == case.? Also, I tried to print the ASCII values of srt1 and str2, they came out to be different. So I think that might be the reason. Now the problem is how does == work for strings?

Your arrays str1 and str2 will decay to pointers to their first elements when you compare them. That is, you compare two pointers that will never be equal.
In short, your comparison str1 == str2 is equal to &str1[0] == &str2[0].
What strcmp does differently is that is compares each character in the first string against each corresponding character in the other string, in a loop.

str1==str2 is comparing the addresses of the strings, not the strings themselves.strcmp will go to these addresses and compare all characters.

Related

Alternative to strlen not breaking on 0 [duplicate]

This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 4 years ago.
Is there any better way of getting the right length of array containing digits?
I have an array of digits: 0, 0, 1 and I try to get length of it. It obviously breaks and returns 0. I am new to C but I tried to make custom strlen function:
int custom_strlen(char *str) {
for(int i = 1; ;i++) {
if (str[i] == 0) {
return i;
}
}
return -47;
}
but it is not that efficient and in some cases returns unexpected values as well. The expected out put would be 3 in this case.
Is there any function to use?
An array of integers is not a string. C arrays do not contain length information inherently. The way strlen works is that C strings are null terminated, meaning the last character is NUL (null character), which is 0. Otherwise, there is just no way to know how long an array is.
I think you may be wanting to do an array of '0','0','1'. Can you post the array you are using?
As mentioned, C strings are null terminated.
The only choices are
Using a string terminated with some special character that you watch for (like a null) or
Keeping track of how long the string is when you create it.
FWIW, if it's not null terminated, it's not actually a string in C, it's just memory that contains chars that you happen to be interpreting as a string.

How to Compare 2 Character Arrays [duplicate]

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 6 years ago.
How do I compare these two character arrays to make sure they are identical?
char test[10] = "idrinkcoke"
char test2[10] = "idrinknote"
I'm thinking of using for loop, but I read somewhere else that I couldnt do test[i] == test2[i] in C.
I would really appreciate if someone could help this. Thank you.
but I read somewhere else that I couldnt do test[i] == test2[i] in C.
That would be really painful to compare character-by-character like that. As you want to compare two character arrays (strings) here, you should use strcmp instead:
if( strcmp(test, test2) == 0)
{
printf("equal");
}
Edit:
There is no need to specify the size when you initialise the character arrays. This would be better:
char test[] = "idrinkcoke";
char test2[] = "idrinknote";
It'd also be better if you use strncmp - which is safer in general (if a character array happens to be NOT NULL-terminated).
if(strncmp(test, test2, sizeof(test)) == 0)
You can use the C library function strcmp
Like this:
if strcmp(test, test2) == 0
From the documentation on strcmp:
Compares the C string str1 to the C string str2.
This function starts comparing the first character of each string. If
they are equal to each other, it continues with the following pairs
until the characters differ or until a terminating null-character is
reached.
This function performs a binary comparison of the characters. For a
function that takes into account locale-specific rules, see strcoll.
and on the return value:
returns 0 if the contents of both strings are equal

C - Comparison of Arrays with == works, why? [duplicate]

This question already has answers here:
C optimisation of string literals
(2 answers)
Closed 7 years ago.
I'm a little bit confused. I have the following function:
int comp(char s1[], char s2[]) {
return s1 == s2;
}
As far as I know this compares only the addresses of the first elements from char array s1 and char array s2.
But strange is if I compare (in Visual Studio) two equal char arrays like
comp("test","test");
I got 1 (true) instead of 0 (false). But should the addresses not be different and therefore the result should be always 0?
I'd say this is the result of a compiler optimisation using the same instance of the string. If you did something like this you'd prove == doesn't work as you suggest:
char s1[10];
char s2[10];
strcpy(s1, "test");
strcpy(s2, "test");
printf("%d\n", comp(s1, s2));
It is so because same strings are stored as one string in the string pool during compilation . Therefore both points to the same address as there is only one "test" string in the string pool.
String literals are often reused by optimizing compilers, so if you use the same string literals twice, both will be the exactly same string literals. And your function are comparing pointers, and as both string literals are the same then you are comparing the same pointers which of course will give you a "true" value.
Read about the concept of mutabe and immutable string. String stored in stack when compared returns true but if one string in heap an other in stack it returns false.
Second question is, are you using prpredefined functions to compare 2 string then the functions works as follows
Compare(s1,s2) returns positive zero or negative according as s1 preced, equals or follows s2 in lexicographical ordering basednon unicide character.
Regards.

Status of array with characters [duplicate]

This question already has answers here:
When initializing a char array, is the remaining space zero filled or uninitialized?
(2 answers)
Closed 9 years ago.
I was declaring a char array like this-
char str[16]= "The world is";
I know that its 13th character will be '\0'. But I am curious about rest of the character values till 16 in str. Are all of them assigned to '\0'. I searched it but could not find a good explanation. So I thought another fastest way is to ask here.:)
The rest will contain zero. What you are actually doing is initializing your array as follows:
char str[16]= {'T','h','e',' ','w','o','r','l','d',' ','i','s','\0'};
If you initialize an array in C that you have given a length, with something that is shorter, C will fill the rest with 0.
Example: this will give an array filled with zero's
int str[16]= {0};
so what you wrote is equivalent to:
char str[16]= {'T','h','e',' ','w','o','r','l','d',' ','i','s','\0',0,0,0};
Note that 0 == '\0' (both 0000...)

C string - identical, and not matching? [duplicate]

This question already has answers here:
Using the equality operator == to compare two strings for equality in C [duplicate]
(9 answers)
Closed 9 years ago.
Got a small problem with C. Restricting myself to simple C (i.e. OS instructions), and two strings seem to not be the same. Here is my code:
char inputData[256];
int rid;
rid = read(0,inputData,256);
// Strip input
char command[rid];
int i;
for (i = 0; i<=rid-2; i++) {
command[i] = inputData[i];
}
command[rid-1] = '\0';
if (command == "exit") {
write(1,"exit",sizeof("exit"));
}
Now, if a user enters "exit" into the terminal when queried and hits enter, the if for detecting "exit" never gets run. Any ideas?
Thanks,
EDIT: I am commiting to git as I go, so the current version can be found at github.com/samheather/octo-os. It's very obviously not complete code, but it demonstrates the problem.
You can't compare strings with ==. You need to use strcmp.
if (strcmp(command, "exit") == 0) {
C strings are actually character arrays. You can think of "command" as a pointer to the first character. You want to compare every character in the string, not just the location of the first characters.
You should use strcmp to compare strings in C.
if(strcmp(command, "exit") == 0) //strcmp returns 0 if strings are equal
To quote:
A zero value indicates that both strings are equal. A value greater than zero indicates
that the first character that does not match has a greater value in str1 than in str2.
a value less than zero indicates the opposite.
As it stands right now, you're comparing the address of command with the address of the string literal "exit", which pretty much can't be the same.
You want to compare the contents, with either strcmp, or (if "only OS instructions" means no standard library functions) an equivalent you write yourself that walks through the strings and compares characters they contain.
As others said, == doesn't work with strings. The reason is that it would compare the pointers given.
In the expression
command == "exit"
command is a pointer to your array variable, while "exit" is a pointer to that string which resides in read-only data space. They can never be identical, so the comparison always is false.
That's why strcmp() is the way to go.
Use strcmp from the standard library.

Resources