简体   繁体   English

char [] vs LPCSTR奇怪的行为

[英]char[] vs LPCSTR strange behavior

Could you please explain why, in order to convert a char array like this: 您能否解释为什么,为了转换如下所示的char数组:

char strarr[5] = {65,83,67,73,73}; //ASCII

Into LPCSTR to be accepted by GetModuleHandleA() and GetProcAddress() , I have to first append 0 to the end ? LPCSTR放入GetModuleHandleA()GetProcAddress()接受的操作中,我必须首先在末尾附加0

ie I have: 即我有:

char strarr[6] = {65,83,67,73,73,0};

And only then convert as (LPCSTR)&strarr . 然后将其转换为(LPCSTR)&strarr

For some reason I don't get the first one works only sometimes (ie if I do not add 0 at the end), while if I do add zero at the end - this work all the time. 出于某种原因,我有时不会获得第一个效果(即,如果我不加0的话),而如果我确实要加0的话-一直都是这样。 Why do I have to add zero? 为什么我必须加零?

Oh and a side question - why in C++ do I have to explicitly state the size of array in [], when I am initializing it with elements right away? 哦,还有一个问题-为什么在C ++中,当我立即用元素初始化数组时,为什么必须在[]中显式声明数组的大小? (If I don't state the size, then it does not work) (如果我没有说明尺寸,那么它将不起作用)

Thanks. 谢谢。

Those functions expect NULL terminated strings. 这些函数期望以NULL终止的字符串。

Since you only give them a pointer to a char array, they can't possibily know its size, hence the need for a particular value (the terminating NULL character) to indicate the end of the string. 由于只给他们一个指向char数组的指针,因此他们可能无法知道其大小,因此需要一个特定的值(终止NULL字符)来指示字符串的结尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM