I'm trying to compare a character array against a string like so:
const char *var1 = " "; var1 = getenv("myEnvVar"); if(var1 == "dev") { // do stuff }
This if statement never validates as true... when I output var1 it is "dev", I was thinking maybe it has something to do with a null terminated string, but the strlen of "dev" and var1 are equal... I also thought maybe var1 == "dev" was comparing "dev" against the memory location of var1 instead of the value. *var1 == "dev" results in an error.... tried many things, probably a simple solution for the saavy c++ developer (I havent coded c++ in a looong time).
edit: we've tried
if(strcmp(var1, "dev") == 0)
and
if(strncmp(var1, "dev", 3) == 0)
Thanks
edit: After testing at home I'm just going to suggest my co-worker changes the datatype to a string. I believe he was comparing a char array of a large size against a string. I put together a program that outputs sizeof, strlen, etc to help us work through it. Thanks to everyone for the help.
A function such as strcmp() will iterate through both strings, checking their bytes to see if they are equal. strcmp() will return 0 if they are equal, and a non-zero value if they differ.
Compare Char in C Using the strcmp() Function in C The strcmp() function is defined in the string header file and used to compare two strings character by character. If both strings' first characters are equal, the next character of the two strings will be compared.
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.
equals(char[] a, char[] a2) method returns true if the two specified arrays of chars are equal to one another. Two arrays are equal if they contain the same elements in the same order.
Use strcmp()
to compare the contents of strings:
if (strcmp(var1, "dev") == 0) { }
Explanation: in C, a string is a pointer to a memory location which contains bytes. Comparing a char*
to a char*
using the equality operator won't work as expected, because you are comparing the memory locations of the strings rather than their byte contents. A function such as strcmp()
will iterate through both strings, checking their bytes to see if they are equal. strcmp()
will return 0 if they are equal, and a non-zero value if they differ. For more details, see the manpage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With