【问题标题】:Why does my string say (null)? [closed]为什么我的字符串说(null)? [关闭]
【发布时间】:2014-10-17 14:13:31
【问题描述】:

我正在尝试根据条件设置文件名,但它不起作用。它一直说(空)。

void main()
{
    int cond = 1;
    char * filename;
    // C:\other\path\here\
    filename = "C:\\other\\path\\here";
    if (cond)
        // C:\some\path\here\
        filename = "C:\\some\\path\\here";

    printf("%s", filename);
}

【问题讨论】:

  • 这不是你的真实代码。
  • ` // C:\other\path\here\ ` 这会将下一行作为注释,因此不会分配文件名。
  • @mohaned - 很好看的先生!
  • 只要使用/作为路径分隔符(包括你的cmets)。 (适用于 Windows,不用担心。)

标签: c++ string


【解决方案1】:

从标准来看,

§2.1.2 [lex.phases]

换行符的每个实例和紧接在前面的 反斜杠字符被删除,拼接物理源行形成 逻辑源代码行。

所以

// C:\other\path\here\
filename = "C:\\other\\path\\here";

变成

// C:\other\path\here\filename = "C:\\other\\path\\here";

同样

// C:\some\path\here\
filename = "C:\\some\\path\\here";

变成

// C:\some\path\here\filename = "C:\\some\\path\\here";

因此文件名永远不会被初始化。

MS C++ 编译器发出警告。

(6) : 警告 C4010: 单行注释包含换行符

(9) : 警告 C4010: 单行注释包含换行符

预处理后,我想这就是代码

void main()
{
    int cond = 1;
    char * filename;

    if (cond)
        printf("%s", filename);
}

其实在上面的程序中filename可以有任何值,不一定是null。所以你的程序可以打印任何东西,崩溃等等。您可能正在编译调试并且您的编译器 null 在调试模式下初始化了未初始化的指针,因此您得到 null Ob:main 始终是 int main 而不是 void main

【讨论】:

    猜你喜欢
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    相关资源
    最近更新 更多