Why whole structure can not be compared in C, yet it can be copied?

后端 未结 6 1683
感情败类
感情败类 2020-12-16 18:08

Why whole structure can not be compared in C yet it can be copied? In other words, Why comparison in below program does not work? It does not print string.

#         


        
6条回答
  •  旧时难觅i
    2020-12-16 18:48

    struct elements are usually aligned to some boundary, and when you initialize a struct (especially one on the stack), anything in the bytes skipped by alignment will be uninitialized. Moreover, the contents of n past the end of the constant initializer are not initialized. struct comparison is defined as s1 == s2 doing memcmp(&s1, &s2, sizeof s1), whereas struct initialization may or may not copy the skipped bytes. If you want to reliably compare structs, you should explicitly compare their elements.

提交回复
热议问题