开发者

Help understanding const char* operators in c++

开发者 https://www.devze.com 2023-03-06 11:00 出处:网络
I need to translate some code from c++ to java, and I am not so sure how to deal with the \'const char*\' operators. Check code below:

I need to translate some code from c++ to java, and I am not so sure how to deal with the 'const char*' operators. Check code below:

const char* handText;
const char* index = strchr(handText, '-');
char handCeil[4];
char handFloor[4];
strncpy(handCeil, handText, index - handText);
strcpy(handFloor, index + 1);

What I got is something like:

String handText;
String index = handText.substring(handText.indexOf('-'));
char handCeil[4];
char handFloor[4];

However, I don't know what it means when you add integers (index + 1), or when you subtract (index - handText) strings in c++. Sorry if this is a stupid 开发者_如何学编程question, but I never learned how to program in c++, only in java. Thank you.


This

strncpy(handCeil, handText, index - handText);
strcpy(handFloor, index + 1);

is equivalent to

int index = handText.indexOf('-'); // I changed this for you
handCeil = handText.substring(0, index+1);
handFloor = handText.substring(index+1);

So it splits the string by the '-' and puts the first part (including the '-' itself, I think) into handCeil and the remainder into handFloor.

index - handText means this: index points to a specific character, handText points to the beginning of that string. If you subtract the two then you get the number of characters between those two pointers, or the array index of the first '-'. strncpy copies n bytes, so if index points to the 3rd character it will copy 3 characters. index + 1 means point to the character 1 after the one pointed to by index.


You cannot muck around with pointers in Java. Either you use String methods such as subString(int startIdx, int endIdx) to extract out substring to assign to handCeil and handFloor. I would prefer keeping them as Java String. If later you need to access the individual characters you could do it anyways through charAt(int idx) method.


Adding one to a char* (pointer) increments the pointer one char.

So in the code provided, since index points to the '-' in handText, incrementing it will cause the pointer to now point to the next character.

(BTW, the C++ code provided isn't at all secure and will cause significant errors for many possible values of handText, like 'this is a string-'. ;)


The snippet invokes undefined behavior.

const char* handText;
const char* index = strchr(handText, '-');

handText is an uninitialized pointer constant. Passing it as a parameter to strchr invokes UB. strchr returns the pointer to the first occurence of - in handText but handText is pointing no where or garbage.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号