C ++在64位平台中传递char数组地址 [英] c++ pass char array address in 64bit platform

查看:172
本文介绍了C ++在64位平台中传递char数组地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有func(),必须带unsigned int参数。

i have func() which must have to take unsigned int parameter.

有一个原因使func(unsigned int val)无效,

there is a reason for void func(unsigned int val),

我必须将各种类型(unsigned char,unsigned short,unsigned int)传递给func参数。

i have to pass various type(unsigned char, unsigned short, unsigned int) to func parameter.

我也必须通过将char数组转换为func(),我的当前解决方案如下面的代码。

and i have to pass char array to func(), my current solution like below code.

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

is there easy way to port this code in 64bit platform?

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

note: intptr_t

推荐答案

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

There are a lot of problem with your code, but at least for me the one the compiler first complains about is:


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

error: cast from pointer to smaller type 'unsigned int' loses information │Offset: 4 byte: 0x7ffe4b93ddd4 contents:9 func((unsigned int)(char *)str);

我假设您正在尝试将char数组的字面地址潜入unsigned int参数中。但是,无符号int只能容纳4个字节(在我的平台上),这不足以容纳完整地址,因为所有指针都需要8个字节(同样在我的平台上)。

I assume that you're trying to sneak in the literal address of the char array into the unsigned int parameter. However an unsigned int can only hold 4 bytes (in my platform), that is not enough to hold the full address, since all pointers require 8 bytes (again, in my platform). See for yourself.

#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;
}

这篇关于C ++在64位平台中传递char数组地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆