[英]Char array, string represents a memory address how can i add value to that address?
我有一個保存內存地址的char數組,例如char add [8] =“ 000AAC88”; 我想將一個字符放入由add數組指定的內存地址中,換句話說,我想在000AAC88的內存地址中使用一個字符,例如'a'。
您可以將strtoull()
的底數strtoull()
16或sscanf()
將ASCII的十六進制數轉換為足夠大的整數,然后將其轉換為指針。 在這里,為了簡單起見,我使用strtoull()
。
如果您的庫以適合您的方式實現它,則還可以使用%p
格式說明符直接在指針及其字符串表示形式之間進行轉換。
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#define HEX_DIGITS_IN_PTR (sizeof(unsigned long long int)*2U)
int main(void)
{
static const char msg[] = "hello, world!\n";
char hex_address[HEX_DIGITS_IN_PTR] = {'\0'};
snprintf( hex_address,
sizeof(hex_address),
"%llX",
(unsigned long long int)(uintptr_t)(void*)&msg );
const char* const converted_ptr =
(void*)(uintptr_t)strtoull( hex_address, NULL, 16 );
fputs( converted_ptr, stdout );
return EXIT_SUCCESS;
}
一旦轉換為char*
,就可以對其進行指針運算。
您認為8個十六進制數字足以容納一個指針的假設將破壞64位代碼。 在本示例中,為簡便起見,我假設unsigned long long int
的寬度足以存儲任何指針。 但是,如果您希望盡可能地具有可移植性和耐將來性,可以將<inttypes.h>
的常量與sscanf()
。 另外,POSIX(和Linux)還提供了寬度受限的環境,以保證unsigned long
的寬度足以容納指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.