You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

字符串字面量类型不符预期,请问"hello"的实际类型是什么?

Type of String Literal "hello" Explained

Hey there! Let's break down the type of string literals like "hello" and touch on why you might be seeing unexpected zero values in your program.

First, the core answer you’re looking for:

  • In C++, the string literal "hello" has an actual type of const char[6]. The 6 accounts for the 5 characters in "hello" plus the mandatory null terminator \0 that the compiler automatically appends to every string literal behind the scenes.
  • In C, the type is technically char[6] (no const qualifier), but this is a holdover from older standards—string literals in C are still read-only, and modifying them will cause undefined behavior (crashes, garbage output, etc.). Modern C compilers will warn you if you try to assign a string literal to a non-const char*.

Common Pitfalls That Might Cause Zero/Unexpected Values

If your program is returning zero instead of what you expected, it’s likely tied to how the string literal is being used:

  • Implicit Array-to-Pointer Conversion: Most contexts will automatically convert the const char[6] array to a const char* pointer pointing to the first character. For example, if you pass "hello" to a function expecting a pointer, or assign it to a pointer variable, you’re no longer dealing with the array type directly.
  • Misusing sizeof: sizeof("hello") will return 6 (the full size of the array), but sizeof(const char*) returns the size of a pointer on your system (usually 4 or 8). If you’re accidentally taking the size of a pointer instead of the array, that might lead to confusing values.
  • Pointer Comparisons: If you’re comparing pointers to string literals, keep in mind that the compiler may store identical literals at the same memory address (or not, depending on compiler settings), which could result in unexpected equality/zero results.

Example to Verify the Type

Here’s a quick C++ snippet to confirm the underlying type using decltype (which preserves the original type of the literal):

#include <iostream>
#include <typeinfo>

int main() {
    // decltype("hello") retains the original const char[6] type
    using HelloType = decltype("hello");
    HelloType arr = "hello";

    std::cout << "Size of the string literal array: " << sizeof(arr) << "\n"; // Outputs 6
    std::cout << "Type name (compiler-dependent): " << typeid(HelloType).name() << "\n";
    return 0;
}

内容的提问来源于stack exchange,提问作者Vincent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:02:37