user2950895
user2950895

Reputation: 27

Converting from integer to string in C

I want to convert an integer to a string in C. I have tried the following code but the program is constantly outputting a 9-digit number. Does someone knows what is the error please and how can I fix it?

int num = 158;
char str[5];
sprintf(str, "%d" ,num);
printf("The result is: %d" , sprintf);

Thanks!

Upvotes: 0

Views: 229

Answers (3)

David Heffernan
David Heffernan

Reputation: 612794

printf("The result is: %d" , sprintf);

This code attempts to print sprintf which is a function. So its address is passed to printf. That's just not what you intended to do. Not to mention the fact that %d with an address leads to undefined behavior.

To print the string you made, you do this:

printf("The result is: %s", str);

Note that you must use the %s format string because the argument you supply is a string.

If all you want to do is to print the value, then you can remove str, remove the call to sprintf, and get printf to perform the formatting:

printf("The result is: %d", num);

One advantage of this is that it avoids you having to decide how large a buffer to allocate. You allocated a buffer with length 5 which can accept numbers up to 4 digits, or 3 digits if negative. For values with more digits, then your code will overrun that buffer.

Upvotes: 2

Marco Guerri
Marco Guerri

Reputation: 942

Either you print the integer with %d

printf("The result is: %d\n", num);

or the string representation with %s

printf("The result is: %s\n" , str);

By doing

printf("The result is: %d" , sprintf);

You are printing the decimal representation of the address of the function sprintf. Example:

#include <stdio.h>
int main() {
int num = 158;
char str[5];
sprintf(str, "%d" ,num);
printf("The result is: %d\n", sprintf);
printf("The result is: %8x\n", sprintf);

}

Compile statically in order to make it easier to locate the address of sprintf.

➜  ~ [4] [Thu 13] $ gcc file.c -o bin -static

In the code, I also print the hexadecimal representation, which is easier to locate in the binary file. Output:

The result is: 4200768
The result is:   401940

You can actually check the linear address of sprintf in the ELF executable:

➜  ~ [4] [Thu 13] $ nm bin | grep sprintf
0000000000480830 W asprintf
0000000000480830 T __asprintf
0000000000480830 T ___asprintf
0000000000401940 T _IO_sprintf
0000000000480a40 T _IO_vasprintf
00000000004019d0 T __IO_vsprintf
00000000004019d0 T _IO_vsprintf
0000000000401940 T sprintf
0000000000401940 T __sprintf
0000000000480a40 W vasprintf
00000000004019d0 W vsprintf

As expected, 0x0000000000401940.

Upvotes: 6

Mohit Jain
Mohit Jain

Reputation: 30489

Change your printf to printf("The result is: %s" , str);.

%s is the specifier for strings and your string name is str. Printing with incorrect % specifiers invoke undefined behavior.

Upvotes: 3

Related Questions