1

I try to convert a decimal number to its its hexadecimal representation (and want to get only the fourth LSB digits). It is seems that my function do works, but when i try to get the value of the number from the main function, i get all the digits and x1!=x2. Where do I wrong?

here is my code:

char* dec_to_hex_converter(int num, char x[])
{
int i = 1;
int size = 0;

sprintf(x, "%04X\n", num);
size = strlen(x);
if (size > 4)
{
    while (size > 4)
    {
        x++;
        size--;
    }
    x--;
}
*(x + 4) = '\0';
printf("x1=%s\n", x);
return x;
}

int main()
{
    char x[10];
    dec_to_hex_converter(-16,x);
    printf("x2=%s\n", x);
}

I want to get FFF0 but when I print the result I get FFFFFFF0 (ONLY OUTSIDE THE FUNCTION)

thanks in advance

Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
shaked
  • 87
  • 1
  • 4

3 Answers3

1

The x pointer that is being printed out inside dex_to_hex_converter() has been moved to the middle of the character array. So only half of the string is printed.

char [] = "FFFFFFF0\0"
               ^
               |
               x

When you return to main(), the pointer x, which was passed by value, returns to its original value pointing to the beginning of the character array, and so, the whole string is once again printed out.

char [] = "FFFFFFF0\0"
           ^
           |
           x

To access only the portion of the string you want...use the pointer returned, not the one passed in :

printf("ret=%s\n", dec_to_hex_converter(-16, x));
Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
0

When you change x in the function, you only change a local pointer that was initialized with the x array from main.

In fact the function declaration is seen by the compiler as:

char* dec_to_hex_converter(int num, char *x)

To really understand it, you could control the return value:

int main()
{
    char x[10];
    char *cur = dec_to_hex_converter(-16,x);
    printf("x2=%s (returned:%s\n", x, cur);
    printf("delta %d\n", cur - x);
    return 0;
}

Output would be:

x1=FFF0
x2=FFFFFFF0 (returned:FFF0)
delta 4
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

You seem to mix some concepts. In your title you mention a string returned by a function.

If you want to return a string you can use it as follows:

int main()
{
    char x[10];
    char *result = dec_to_hex_converter(-16,x);
    printf("x2=%s\n", result);
}

In your code you try to change the passed pointer. This would require to pass a "reference" to it instead of the pointer itself. (In C there are no real references. You need to pass a pointer to the pointer instead)

And most important you need to pass a modifyable lvalue to the function. The address of an array is not modifyable.

Gerhardh
  • 11,688
  • 4
  • 17
  • 39