char[] vs LPCSTR strange behavior

245 views Asked by At

Could you please explain why, in order to convert a char array like this:

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 ?

i.e. I have:

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

And only then convert as (LPCSTR)&strarr.

For some reason I don't get the first one works only sometimes (i.e. if I do not add 0 at the end), while if I do add zero at the end - this work all the time. 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? (If I don't state the size, then it does not work)

Thanks.

1

There are 1 answers

4
ereOn On BEST ANSWER

Those functions expect NULL terminated strings.

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.