不同的字符串如何具有相同的地址 [英] How can different strings have the same address

查看:179
本文介绍了不同的字符串如何具有相同的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,为了比较C中的两个字符串,您需要使用strcmp()函数. 但是我试图用==运算符比较两个字符串,并且它起作用了.我不知道怎么做,因为它只是比较两个字符串的地址.如果字符串不同,则不起作用.但是后来我打印出了字符串的地址:

I know that in order to compare two strings in C, you need to use the strcmp() function. But I tried to compare two strings with the == operator, and it worked. I don't know how, because it just compares the address of the two strings. It shouldn't work if the strings are different. But then I printed the address of the strings:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char* str1 = "First";
    char* str2 = "Second";
    char* str3 = "First";

    printf("%p %p %p", str1, str2, str3);

    return 0;
}

输出为:

00403024 0040302A 00403024
Process returned 0 (0x0)   execution time : 0.109 s
Press any key to continue.

str1str3如何具有相同的地址?它们可能包含相同的字符串,但它们不是相同的变量.

How is it possible that str1 and str3 have the same address? They may contain the same string, but they aren't the same variable.

推荐答案

不能保证总是这样.通常,实现者维护一个文字池,该文字池仅将每个字符串文字维护一次,然后对于字符串文字的多次使用,将使用相同的地址.但是人们可能会以不同的方式实现它-标准并没有对此施加限制.

There is no guarantee that it will always be like this. In general, implementors maintain a literal pool maintaining each of the string literals only once, and then for multiple usages of the string literal the same address is being used. But one might implement it a different way - the standard does not pose a constraint on this.

现在您的问题:您正在查看指向同一字符串文字的两个指针的内容.相同的字符串文字会产生相同的值(它们衰减为指向第一个元素的指针).但是由于第一段中所述的原因,该地址是相同的.

Now your question: You are looking at the content of the two pointers pointing to the same string literal. The same string literal gave rise to the same value (they decayed into a pointer to the first element). But that address is same because of the reason stated in the first paragraph.

此外,我还要强调提供%p格式说明符的参数和(void*)强制转换.

Also, I would emphasize providing the argument of the %p format specifier with the (void*) cast.

这篇关于不同的字符串如何具有相同的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆