相关疑难解决方法(0)

两个字符串指向不同字符串文字的地址是相同的

#include<stdio.h>
#include<string.h>

int main()
{
    char * p = "abc";
    char * p1 = "abc";
    printf("%d %d", p, p1);
}
Run Code Online (Sandbox Code Playgroud)

当我打印两个指针的值时,它打印相同的地址.为什么?

c pointers literals

80
推荐指数
4
解决办法
6126
查看次数

两个字符串文字具有相同的指针值?

当我使用MinGW运行此程序时,我输出为"="

#include<iostream>

using namespace std;

int main()
{
 char *str1 = "Hello";
 char *str2 = "Hello";

 if(str1==str2)
 cout<<"=";
 else
 cout<<"!=";


 return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,从逻辑上讲,它应该是!=,因为这些是指针,它们指向不同的内存位置.当我在Turbo C++中运行此代码时,我得到了!=

c++ string pointers

8
推荐指数
2
解决办法
1784
查看次数

String Literal address across translation units

I'd like to ask if is it portable to rely on string literal address across translation units? I.e:

A given file foo.c has a reference to a string literal "I'm a literal!", is it correct and portable to rely that in other given file, bar.c in instance, that the same string literal "I'm a literal!" will have the same memory address? Considering that each file will be translated to a individual .o file.

For better illustration, follows an …

c c++ string pooling string-literals

7
推荐指数
1
解决办法
846
查看次数

可以在编译时索引数组吗?

对另一个问题的评论中,用户hvd声明了以下内容:

...虽然字符串文字可以传递给constexpr函数,并且在常量表达式中的字符串文字上允许数组索引,但constexpr函数参数的索引操作不符合常量表达式.

我并不完全明白这是什么意思.这是否意味着hash_value以下代码中的变量

#include <cstddef>

// Compute the hash of a string literal adding the values of its characters
template<std::size_t N> constexpr std::size_t
hash_string
    ( const char (& s)[N] )
noexcept
{
    std::size_t h = 0;

    // Array indexing happening under the hood
    for ( const auto c : s )
        h += c;

    return h;
}

constexpr auto hash_value = hash_string("Hello, world!");
Run Code Online (Sandbox Code Playgroud)

无法在编译时进行评估?你能详细说明引用的评论并告诉我是否正确吗?

c++ arrays constant-expression constexpr c++14

6
推荐指数
1
解决办法
252
查看次数