C++ pointer arithmetic weirdness

十年热恋 提交于 2019-12-02 07:50:56
Skizz

That looks fine to me. The line:

 (pst1 + np1)

adds np1 instances of st_one to what pst1 points at, which means that pst1s value is incremented by np1 * sizeof (st_one) bytes, which is 25 (sizeof = 5), which corresponds to the values you've outputted. Instead of the above, I think you wanted:

 (pst1 + 1)

The pc1 value works because that is a char pointer, so the line:

(pc1 + np1)

adds np1 * sizeof (char) bytes to pc1, which is 5 bytes.

Incrementing a pointer makes the pointer point to the next element in memory, not the next byte.

You shouldn't add sizeof(x), because that is done automatically. When you increment a pointer, like ++p, the address is incremented by the size of the object, so that it points to the next one.

Adding 1 to a pointer is the same as ++p. Adding sizeof(x) scales the increment twice.

Your calculations work fine for char, because sizeof(char) is 1.

C++ automatically multiplies the integer you're adding by the size of the element the pointer points to. It assumes you want to advance the pointer by whole elements, not bytes.

Pointer arithmetic in C and C++ is done times the sizeof the pointed to type of the pointer. That is, int *abc = /* ... */; int *def = abc + 1 results in def having a result an int ahead of abc, not a char.

As for your casting of the pointers into longs, that's implementation defined behavior, so you might get strange results on different machines from doing that.

(For that matter, so is your casting between pointer types. C++ says that's implementation defined too)

It looks like you got everything wrong. For example, for get pst2 from pst1, you have to increment it by one, as pointer pst1 is of type st_one *, so you have to write like this:

pst2 = (st_two*)(pst1 + 1);

.. but you have:

pst2 = (st_two*)(pst1 + np1);

... where np1 is a sizeof of st_one, so it will skip as many st_one structures as that structure has bytes...

Read some docs on pointer arithmetic, like this one.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!