【问题标题】:c++ pass char array address in 64bit platform [closed]c ++在64位平台中传递char数组地址[关闭]
【发布时间】:2017-03-24 02:38:22
【问题描述】:

我有 func() 必须采用 unsigned 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("%s\n", test_str);
}

int main()
{
  char str[128] = "hello world";
  func((unsigned int)(char *)&str); //current my solution
  return 0;
}

注意:intptr_t

【问题讨论】:

  • 这是 C++ 吗?当我看到很多演员表时,通常表明程序员做错了什么
  • 函数必须是无符号整数,我应该把它改成模板吗?
  • 为什么要有unsigned int?为什么将 printf 用于 C++ 代码?为什么你把它标记为 C?
  • 这听起来像an XY problem。
  • 传递一个char数组的地址如下:DoSomething(&charArray); 除此之外,我不知道你在问什么?

标签: c++ arrays


【解决方案1】:

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

错误:从指针转换为更小的类型 'unsigned int' 丢失 信息│偏移量:4字节: 0x7ffe4b93ddd4 内容:9 func((unsigned int)(char *)str);

我假设您正试图将 char 数组的文字地址潜入 unsigned int 参数中。然而,一个 unsigned 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;
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-12
  • 2014-03-07
  • 2013-08-19
  • 2014-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多