Похожие чаты

Hey Can I copy a segment of a pointer to another

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)

15 ответов

13 просмотров

I think you can use memcpy for that here

Sahand-🏔️ Автор вопроса
Pavel
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));

Sahand 🏔️
Do you mean something like this int* ptr = (int*)...

You need also to malloc memory for tmp as far as I know

Sahand 🏔️
Do you mean something like this int* ptr = (int*)...

And also use sizeof(int)*5 as the size otherwise you will copy only 5 bytes

Sahand-🏔️ Автор вопроса
Sahand 🏔️
screenshot why don't I get my 38 for tmp+ 4?

You copy 5 bytes, not 5 elements. Multiply 5 by sizeof(int)

Sahand-🏔️ Автор вопроса

You mean the third argument for memcpy ? Is it calculated in bytes ?

Sahand-🏔️ Автор вопроса
Pavel
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

Sahand 🏔️
Can I also push a range of a pointer to another? L...

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)

Sahand-🏔️ Автор вопроса

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.

Sahand-🏔️ Автор вопроса

Похожие вопросы

Обсуждают сегодня

Если у меня есть такой класс: Object = {} function Object:new(a_name, a_transform, a_color, a_mesh, a_material, a_shader, a_textures) local private = {} private.n...
Cuarno Vile
4
А кто-то пробовал, уезжая из Эстонии получить э-рез и продолжить вести предпринимательскую деятельность внутри Эстонии, используя свой OÜ?
Lalalashechki Lalala
62
Is Kadena onto something special? No one really knows. Good luck!
Bright Uncle Stephen EqualBet
40
At which price point will BCH, an ASIC mined coin, be succeptible to reorg attacks because of low hashrate? $10? $1? $0.1? $0.01?
Kishniev
18
я не магистр хаскеля, но разве не может лейзи тип конвертнуться в не-лейзи запросив вычисление содержимого прям при инициализации?
deadgnom32 λ madao
100
Гайз, кто-нибудь пробовал запустить probe-rs под камень, которого нет в probe-rs? Мб есть какой-нибудь пример у кого... Через target-gen попробовал сгенерировать chip-descript...
Максим Смирнов
2
зачем же переименовывать ? чтобы кол-во участников возросло или вдруг IBM от этого снова на свифте начнет кодить ? Я не понимаю что страшного в том что свифт гавно, если это т...
Oleh Nerzh
10
I hodl ocean for a long time. Is there new development that I should read?
A33
12
Is there an article I can read for more information?
Lobaka
10
здравствуйте. совершаю вот такую вещь: strcpy(line, (char)current_number); где current number — неподписанный шорт, line — массив чаров. ругань следующая: main.c:29:30: error...
Roberto's Ширгозиев
13
Карта сайта