The meaning of adding and subtracting string pointers

When writing file IO, you need to use the file name and path, and found the problem of the meaning of addition and subtraction in the strncpy function string

  char str1[64] = "1:/45/789/b";             //文件路径+文件名

  const char *fullname = str1;               //文件路径+文件名
  const char *p = strrchr(fullname, '/');    //文件名
  char dirname[256] = {
    
    0};

  
  strncpy(dirname, fullname,p-fullname+1);   //文件路径
  std::cout << "路径:"<<dirname << std::endl;
  std::cin.get();
  return 0;
  //  变量p和filename实际内存地址,--vs2017
  //       p: 0x004ffd5d
  //fullname: 0x004ffd54   //根据16进制地址位,相差9个字节。

}

In the string pointer, the subtraction of the two pointers is the difference in the memory address, divided by the byte size of the pointer type.

High address pointer-low address pointer is positive

Low address pointer-high address pointer is negative

Guess you like

Origin blog.csdn.net/Matcha_/article/details/113140119