in any way?
Example:
int* ptr = (int*)malloc(10 * sizeof(int));
*(ptr + 0) = 23;
*(ptr + 4) = 38;
*(ptr + 9) = 91;
int* tmp = (ptr + 5);
So tmp will only contain first six integers that ptr has (from index 0 to 5)
I think you can use memcpy for that here
Do you mean something like this int* ptr = (int*)malloc(10 * sizeof(int)); *(ptr + 0) = 23; *(ptr + 4) = 38; *(ptr + 9) = 91; int* tmp = NULL; memcpy(tmp, ptr, 5); printf("%d %d %d", *(tmp + 0), *(tmp + 5), *(tmp + 9));
You need also to malloc memory for tmp as far as I know
And also use sizeof(int)*5 as the size otherwise you will copy only 5 bytes
And still tmp+9 will be UB
You copy 5 bytes, not 5 elements. Multiply 5 by sizeof(int)
You mean the third argument for memcpy ? Is it calculated in bytes ?
Yes, as far as I know
Can I also push a range of a pointer to another? Like from index 7 to the index 12. Or do I need a for loop to do that
You can shift your source pointer to achieve that. E.g. if you want to copy elements from 2 to 5 (inclusive), you can do memcpy(tmp, ptr + 2, sizeof(int) * 4); It will put elements from ptr on positions 2, 3, 4, 5 into tmp on positions 0, 1, 2, 3 (assuming that ptr is a pointer of the correct type)
You're dereferencing a pointer which is not initialized and this results in UB (at least in C++) use std::construct_at instead of * there I think.
About which line are you talking about
dereferencing operator
Обсуждают сегодня