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.
Related
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.
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.
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
This question already has answers here:
Issue with main arguments handling
(3 answers)
Closed 7 years ago.
I am fairly new to C, so am not overly familiar with it's syntax, however I have debugged my code and researched for the correct syntax, and it seems to be correct, I have also changed the scope of the variables to see if this was causing the error.
The if statement should compare two variables, which both hold strings, I have even printed both the variables out to ensure they are the same, however it is still skipping straight to the else section of the if statement. Can anyone give me any pointers on why it will not run the if statement, it just skips straight to 'incorrect'.
The correctWord variable is defined at a different section in the code.
Find full code here.
-UPDATE-
I have now updated the syntax of the code, however it is still returning false.
char correctWord[20];
void userGuess(){
char userWordGuess[20];
printf("Anagram: ");
printf(anagramWord);
printf("Your Guess: ");
scanf("%s",userWordGuess); //Reads in user input
printf(correctWord);
printf(userWordGuess);
if(strcmp(userWordGuess, correctWord) == 0){
printf("Congratulations, you guessed correctly!");
}else{
printf("Incorrect, try again or skip this question");
}
}
You cannot compare strings in C using ==, because this compares the addresses of the strings, not the contents of the string. (which you certainly don't require, and obviously, the addresses of the two strings are not equal too.)
C has a pretty nice function for it : strcmp() which returns 0 if both the strings are equal.
Try using this in your if condition:
if (!strcmp(userWordGuess,correctWord))
{
//Yay! Strings are equal. Do what you want to here.
}
Be sure to #include <string.h> before using strcmp().
In C, you can't compare strings using ==. You will end up comparing the addresses of the strings, which is not the same.
You need to call the strmcp() function, which will return 0 if its arguments (two strings) are equal.
So the code should be if(strcmp(userWordGuess, correctWord) == 0).
You're comparing addresses of different arrays, which will always be unequal.
You need to use strcmp or some other strings library function to compare strings character by character.
userWordGuess == correctWord will compare the pointers (i.e. the locations in memory of the arrays), which are probably not equal.
For string comparision in C, use strcmp (or strncmp):
if (!strcmp(userWordGuess, correctWord)){
/*Strings are equal*/
Use
if(strcmp(userWordGuess, correctWord) == 0) // strings are equal
{
printf("Congratulations, you guessed correctly!");
}
else // not equal
{
printf("Incorrect, try again or skip this question");
}
if both string are equal than if condition will run. otherwise it wil run else
The strings are not first-class citizens in the C language. The strings are represented as either arrays of characters or pointers to such arrays.
In both cases, the variable you use to access the string is a synonym for the address in memory of the first character of the string.
What you compare with userWordGuess == correctWord is not the strings but their addresses in memory. Since userWordGuess and correctWord are two different arrays of characters, their addresses in memory are always different and their comparison will always produce FALSE.
In order to compare the actual string values you have to use the standard function strcmp() or one of its variants (find them at the bottom of the documentation page).
Change in the code:
/** Need to include the header that declares the strcmp() function */
#include <string.h>
char correctWord[20];
void userGuess(){
char userWordGuess[20];
/** stripped some lines here ... */
/** compare the strings, not their addresses in memory */
if (strcmp(userWordGuess, correctWord) == 0) {
/** the rest of your code */
What you are doing here is comparing two pointers. userWordGuess and correctWord point each to the beginning of an array of characters (which is what you defined at the beginning of your example code).
So if you want to compare the two arrays of chars you can use the strcmp function defined in string.h
It is important that you learn the relation between arrays and pointers. Pointer arithmetic is as well important here. Check this out: Arrays, Pointers, Pointer Arithmetic
This question already has answers here:
Why is "a" != "a" in C?
(11 answers)
Closed 8 years ago.
I have written the following program:
#include <stdio.h>
main()
{
if("ddd" == "ddd")
printf("equal");
else
printf("not equal");
}
The output is "equal", but according to me, the output should be "not equal" because the string literals are stored in the literal pool or some read only memory (I guess it depends on OS), so both strings should have two different addresses as they are stored at different addresses in memory.
Previously, I have done the same type of example (one year back), and that time the output was "not equal". Now, could anyone tell me, is this due to a change in the C standard, or am I missing something?
It's unspecified for string literals with the same content to have the same address or not. So the output of your program could be equal or it could be not equal, your compiler happens to put them in the same place.
C11 6.4.5 String literals
It is unspecified whether these arrays are distinct provided their elements have the
appropriate values.
Of course, what you do in that condition is a comparison between pointers (use strcmp to compare C strings).
So, I think it is a compiler translation/optimization that "maps" identical literals at the same location in the memory.
EDIT 1:
The following sample confirms what I wrote:
#include <stdio.h>
char* a = "ddd";
char* b = "ddd";
char* c = "ddd";
int main() {
printf ("a => %p\nb => %p\nc => %p\n", a, b, c);
}
The previous program, compiled with gcc using -O0 and executed will print:
a => 0x40060c
b => 0x40060c
c => 0x40060c
I don't know how other compilers will treat the same situation.
When you're comparing two character values (which are not pointers), it is a numeric comparison.
But when you're comparing two string, Base address of strings are compared.If supposed compilers treats as both string are in same location ,then o/p is equal.Otherwise Not.
What you are comparing the two memory addresses for the different strings, which are stored in different locations.so,Not equal.
Even it is read only memory,you are used this for comparison only.You are not modify or not write anything.