字符串末尾的“$”标记是否有特殊含义?
请参考我在某个c程序中看到的代码:
#define _BUILD_DATE "2010/05/03$"
#define _BUILD_TIME "10:46:42$"
#define _BUILD_GUEST "Intel$"
#define _BUILD_BOARD "B0$"
#define _BUILD_CODEVER "2.00$"
const unsigned char SIGN_DATE[] = {_BUILD_DATE};
const unsigned char SIGN_TIME[] = {_BUILD_TIME};
const unsigned char SIGN_GUST[] = {_BUILD_GUEST};
const unsigned char SIGN_PCBV[] = {_BUILD_BOARD};
const unsigned char SIGN_CODEVR[] = {_BUILD_CODEVER};
我很好奇为什么每个字符串的末尾总是有一个“$”标记。首先,我想,一旦我用“{”和“}”声明了一个字符串,我就应该遵循这个规则,但是下面的测试表明它仍然可以正常工作。
#include <stdio.h>
unsigned char A[] = {"ABC$"};
//unsigned char A[] = {"ABC"};
unsigned char B[] = "123";
int main()
{
int i,j;
for(i=0;i<sizeof(A);i++)
{
if(A[i] == ' ')
printf("nulln");
else
printf("%cn",A[i]);
}
printf("n");
for(j=0;j<sizeof(B);j++)
{
if(B[j] == ' ')
printf("nulln");
else
printf("%cn",B[j]);
}
printf("size of A is %dn",(int)sizeof(A));
printf("size of B is %dn",(int)sizeof(B));
return 0;
}
所以我不确定“$”在某些情况下是否有任何特殊含义,或者它只是一个无意义的标记。
谢谢你的时间!
回答
所以我不确定“$”在某些情况下是否有任何特殊含义,或者它只是一个无意义的标记。
简答
它在 C 中没有特殊含义。不在核心语言中,也不在任何库函数中按照惯例。库函数将零视为终止符。
长答案
我不能说它在该特定代码中是否意味着什么。很有可能。但总的来说,它并没有什么特别的意义。一个疯狂的猜测是字符串在某处用作正则表达式。那么它就有了意义。
但更好的猜测是它与 DOS 使用美元终止字符串的事实有关。在 DOS 中,您可以使用中断 9 打印 $ 终止的字符串。您的程序可能具有依赖于此的打印功能。或者也许有一些工具可以分析依赖于此的可执行文件。
这是使用 DOS 中断的 x86 程序集中的 Hello World。
; hello-DOS.asm - single-segment, 16-bit "hello world" program
;
; assemble with "nasm -f bin -o hi.com hello-DOS.asm"
org 0x100 ; .com files always start 256 bytes into the segment
; int 21h is going to want...
mov dx, msg ; the address of or message in dx
mov ah, 9 ; ah=9 - "print string" sub-function
int 0x21 ; call dos services
mov ah, 0x4c ; "terminate program" sub-function
int 0x21 ; call dos services
msg db 'Hello, World!', 0x0d, 0x0a, '$' ; $-terminated message
请注意,这0x0d, 0x0a只是为了打印换行符。在 DOS(以及 Windows)上,在换行符 (0a) 之前需要一个回车符 (0d)。
我在这里找到了代码https://montcs.bloomu.edu/Information/LowLevel/Assembly/hello-asm.html
在 C 中,字符串的结尾是零终止符。