#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)
当我打印两个指针的值时,它打印相同的地址.为什么?
当我使用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++中运行此代码时,我得到了!=
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 …
在对另一个问题的评论中,用户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)
无法在编译时进行评估?你能详细说明引用的评论并告诉我是否正确吗?