C++ 在 64 位平台中传递字符数组地址

c++ pass char array address in 64bit platform

本文关键字:字符 数组 组地址 平台 C++      更新时间:2023-10-16

我有func((,它必须采用无符号的int参数。

void func(unsigned int val(是有原因的,

我必须将各种类型(无符号字符、无符号短字符、无符号整数(传递给 func 参数。

必须将 char 数组传递给 func((,我当前的解决方案如下代码。

编辑:有没有简单的方法可以在64位平台上移植此代码?

char test_str[128] = { 0 };
void func(unsigned int val)
{
  memcpy(test_str, (char *)val, 128); //current my solution
  printf("%sn", test_str);
}
int main()
{
  char str[128] = "hello world";
  func((unsigned int)(char *)&str); //current my solution
  return 0;
}

注:intptr_t

你的代码有很多问题,但至少对我来说,编译器首先抱怨的是:

错误:从指针强制转换为较小的类型"无符号 int"丢失 信息 │偏移量:4 字节: 0x7ffe4b93ddd4 内容:9 func((unsigned int((char *(str(;

我假设您正在尝试将 char 数组的文字地址潜入无符号的 int 参数中。然而,一个无符号的int只能容纳4个字节(在我的平台上(,这不足以容纳完整的地址,因为所有指针都需要8个字节(同样,在我的平台中(。你自己看吧。

#include <stdio.h>
int main (int argc, char  *argv[])
{
    char str[128] = "hello world";
    unsigned int *address = (unsigned int *)str;
    printf("address: %p t contains: %s t pointer size: %lu n", address, (char *)address, sizeof(char *));
    // address: 0x7ffcf9492540          contains: hello world          pointer size: 8
    printf("Size of address in pointer: %lu n", sizeof(long long *));
    // will print the same size as the past sizeof() operation
    printf("Size of unsigned int variable: %lu n", sizeof(unsigned int));
    // 4 bytes, not enough to fit in the necessary 8 bytes
    return 0;
}