我必须复制存储为数组的 Mac 地址,并使用指向另一个的指针引用。我想执行交换,但我不知道我是否复制正确。
uint8_t * custom_mac_store;
memcpy(custom_mac_store, ehdr->ether_shost, sizeof(ehdr->ether_shost));
memcpy(ehdr->ether_shost, ehdr->ether_dhost, sizeof(ehdr->ether_shost));
memcpy(ehdr->ether_dhost, custom_mac_store, sizeof(ehdr->ether_shost));
ehdr->ether_shost指的是一个Mac地址,长度为48位,存储在6个数组中作为8位。
struct sr_ethernet_hdr
{
#ifndef ETHER_ADDR_LEN
#define ETHER_ADDR_LEN 6
#endif
uint8_t ether_dhost[ETHER_ADDR_LEN]; /* destination ethernet address */
uint8_t ether_shost[ETHER_ADDR_LEN]; /* source ethernet address */
uint16_t ether_type; /* packet type ID */
} __attribute__ ((packed)) ;
提前致谢!!!
最佳答案
custom_mac_store 是一个指针,不是一个数组,您应该按照以下方式分配内存:
uint8_t * custom_mac_store = malloc(sizeof(ehdr->ether_shost) * sizeof(uint8_t));
然后做memcpy
这样你可以删除或覆盖 ehdr->ether_shost 但你已经将你的数组复制到新数组。
@alk 你是对的,你需要删除内存
uint8_t * custom_mac_store = malloc(sizeof(ehdr->ether_shost) * sizeof(uint8_t));
memcpy(custom_mac_store, ehdr->ether_shost, sizeof(ehdr->ether_shost));
memcpy(ehdr->ether_shost, ehdr->ether_dhost, sizeof(ehdr->ether_shost));
memcpy(ehdr->ether_dhost, custom_mac_store, sizeof(ehdr->ether_shost));
free(custom_mac_store); //< Destroys everything in the array
custom_mac_store = NULL; //< NULL must be defined in a macro preferanly DEFINE NULL 0
或者你可以使用c++
uint8_t * custom_mac_store = new uint8_t[sizeof(ehdr->ether_shost)];
std::copy ( ehdr->ether_shost, ehdr->ether_shost+sizeof(ehdr->ether_shost), custom_mac_store );
std::copy ( ehdr->ether_dhost, ehdr->ether_dhost+sizeof(ehdr->ether_shost), ehdr->ether_shost );
std::copy ( custom_mac_store, custom_mac_store+sizeof(ehdr->ether_shost), ehdr->ether_dhost );
delete[] custom_mac_store; //< Destroys everything in the array
或者你可以使用堆栈而不是堆(这应该更快,只是不要破坏堆栈)
const std::size_t size_custom_mac_store = 48000;
uint8_t custom_mac_store[size_custom_mac_store]; //< The size must be either a const or a macro
std::copy ( ehdr->ether_shost, ehdr->ether_shost+sizeof(ehdr->ether_shost), custom_mac_store );
std::copy ( ehdr->ether_dhost, ehdr->ether_dhost+sizeof(ehdr->ether_shost), ehdr->ether_shost );
std::copy ( custom_mac_store, custom_mac_store+sizeof(ehdr->ether_shost), ehdr->ether_dhost );
delete[] custom_mac_store; //< Destroys everything in the array
祝你好运。
PS:大爱内存管理,唯我独尊
关于c - 如何在C中将一个数组的数据复制到另一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22020569/