Error 404
Error 404

Reputation: 429

convert int to string pointer C

Write a function the gets two strings and number, the signiture of the function: void get_formated_integer(char *format, char *result, int num) the function convert the given number num according the format and returns a string in the variable result, for %b converts int to binary of the number, for example, for the call: get_formated_integer("%b",&result, 18); then *result will get the string 10010

My code:

   #include <stdio.h>
  void convert_binary(int num)//converts decimal number to binary
{
    if(num>0)
    {
    convert_binary(num/2);
    printf("%d", num%2);
    }

}

void get_formated_integer(char *format, char *result, int num)
{
    if(format[1]=='b')
      convert_binary(num);
}

int main()
{
    char result[100];
    get_formated_integer("%b",&result, 18);
}

My output:

10010

I don't understand how to do that *result will get the string 10010

sorry about my English

Upvotes: 1

Views: 2061

Answers (2)

MarianD
MarianD

Reputation: 14181

First, replace

void convert_binary(int num)//converts decimal number to bi

with

void convert_binary(int num, char * result) //converts decimal number to binary

for the sake to have a place (result) for storing the result.


Second, replace its body - recursive calling and direct printing

{
    if(num>0)
    {
    convert_binary(num/2);
    printf("%d", num%2);
    }
}

with

{
    static int i = 0;              // Offset in result for storing the current digit
    if(num>0)
    {
        convert_binary(num/2, result);
        sprintf(result+i, "%d", num % 2);
        ++i;
    } else 
        i = 0;
}

i.e. with statements for recursive call (updated function) and storing partial values.


Third, following previous changes, replace your original definition

void get_formated_integer(char *format, char *result, int num)
{
    if(format[1]=='b')
      convert_binary(num);
}

with

void get_formated_integer(char *format, char *result, int num)
{
    if(format[1]=='b')
        convert_binary(num, result);       // Only this is different
}

Four, put at the end in your main() function the statement for printing the result (as we changed direct printings in recursive calls to storing):

    printf("%s\n", result);

Upvotes: 0

Paul92
Paul92

Reputation: 9062

result is a pointer to a memory region. I will try to provide a short explanation, you will find more about pointers here (and I strongly suggest you read this tutorial).

When you declare char result[100] you allocate a memory region for 100 characters. A pointer is a variable that has as value a memory address, so you can change the values at a memory address. Basically, what your function should do is to make a string with the formatted number and place it at the memory address indicated by result.

Upvotes: 1

Related Questions