-2

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

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

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

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

Edit: 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;
}

note: intptr_t

sailfish009
  • 2,561
  • 1
  • 24
  • 31

1 Answers1

4

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

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

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;
}
senex
  • 447
  • 3
  • 14