Understanding Char Array equality in C

后端 未结 5 870
忘了有多久
忘了有多久 2021-01-19 13:47

Sorry in advance for the ignorance. I don\'t fully understand how to compare char arrays in C. I was originally comparing two char arrays in c with the simple ==

5条回答
  •  被撕碎了的回忆
    2021-01-19 14:48

    String Literals are stored in contiguous memory locations in Text(Read Only) segment of the memory.

    char *a = "test";
    char *b = "test";
    if (a == b) ..do something
    

    Here you are comparing the address of the first elements of the arrays. This can results in equality as "test" being an String stored in text segment of the memory and *a and *b might point to that memory location.

    char *a = "test";
    char *b = "test";
    if (0 == strcmp(a, b)) ..do something
    

    Here you are comparing each element of both arrays byte by byte till NULLCHAR(\0) for any one of the input array is reached.

提交回复
热议问题