const char* equals char[] | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

const char* equals char[]

Hi all, does anyone know where to put the "\0" to make const char* equal to char[]? If I run this code, one() returns 1 and zero() returns 0, which is kinda strange to me, but I think the "\0" should be able to fix that up somehow. Please let me know! #include <stdio.h> char one(), zero(); int main() { printf("One: %c\n", one()); printf("Zero: %c", zero()); } char one(){ //Outputs 1 unsigned long long int a = 0.0f; const char b = .0; return a == b ? '1' : '0'; } char zero(){ //Outputs 0 const char* p = "sololearn"; char q[] = "sololearn"; return q == p ? '1' : '0'; } https://code.sololearn.com/coPR0HmE5czM/?ref=app

22nd May 2020, 10:58 AM
Orville Vroemen
Orville Vroemen - avatar
3 Answers
+ 3
That's not the cause of the problem here, it's that you can't compare strings with ==. Have a look at the strcmp function in string.h: http://www.cplusplus.com/reference/cstring/strcmp/ EDIT: with == you are comparing the pointers. The pointers point to different memory locations hence they aren't equal.
22nd May 2020, 11:07 AM
Schindlabua
Schindlabua - avatar
+ 1
Thank you Schindlabua, I forgot to dereference the q and the p, *q == *p returns 1.
22nd May 2020, 2:51 PM
Orville Vroemen
Orville Vroemen - avatar
+ 1
Orville Vroemen Careful though, that will only compare the first character!
22nd May 2020, 3:55 PM
Schindlabua
Schindlabua - avatar