-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

8
  • 1
    Is this C++? When I see lots of casts it usually indicates the programmer is doing something wrong
    – Ed Heal
    Mar 24, 2017 at 2:40
  • function must have unsigned int, should i change it to template? Mar 24, 2017 at 2:42
  • Why should it have an unsigned int? Why using printf for C++ code? Why have you tagged it C?
    – Ed Heal
    Mar 24, 2017 at 2:43
  • 2
    This sounds like an XY problem.
    – R Sahu
    Mar 24, 2017 at 2:45
  • 1
    Pass the address of a char array as follows: DoSomething(&charArray); Apart from that, I have no idea what you're asking? Mar 24, 2017 at 2:58

1 Answer 1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.