3

How do I get from:

int i = 1023  

to:

char string[4] = "1023"

Here's my attempted code:

Attempt 1

#include <stdio.h>

main(){

    int avg_adc = 1023;
    char myString[4];
    sprintf(myString, "%d", avg_adc); 
}  
//Output returned 4

Attempt 2

main(){

    int avg_adc = 1023;
    char myString[4];
    snprintf(myString, 4, "%d", avg_adc); 
}  
//Output returned 4

Does these outputs not make myString == char myString[4] = "1023"; ?

I'm just really confused how to get the output I need.

Steven
  • 5,654
  • 1
  • 16
  • 19
Arch
  • 47
  • 2

4 Answers4

9

You need to allocate 5 elements for myString ('1','0','2','3','\0')

#include <stdio.h>

int main(void){
  int avg_adc = 1023;
  char myString[5];
  sprintf(myString, "%d", avg_adc);
  printf("%s\n", myString);
  return 0;
}
amdixon
  • 3,814
  • 8
  • 25
  • 34
jh314
  • 27,144
  • 16
  • 62
  • 82
1

From ISO C11 draft n1570:

The sprintf function returns the number of characters written in the array, not counting the terminating null character, or a negative value if an encoding error occurred.

In other words, the return value of

sprintf(myString, "%d", 1023);

is indeed 4, but it actually writes 5 characters to myString. More is revealed with snprintf, which limits the number of characters written to the specified value, and this number should account for the terminating null character:

Thus, the null-terminated output has been completely written if and only if the returned value is nonnegative and less than [the specified limit].

int avg_adc = 1023;
char myString[4];
int charsWritten;

charsWritten = snprintf(myString, sizeof(myString), "%d", avg_adc);
if (charsWritten >= 0 && charsWritten < sizeof(myString)) {
    printf("OK :-)\n");
} else {
    printf("TROUBLE :-(\n");
    printf("Returned: %d\n", charsWritten);
    printf("myString=%s, expected %d\n", myString, avg_adc);
}

Output on my system:

TROUBLE :-(
Returned: 4
myString=102, expected 1023

In other words, you need to check the return value of snprintf. If the test fails, then your result string was truncated, and it needs to be one character larger than the return value to fit all of the characters that you want it to store, assuming a negative value isn't returned. Declaring char myString[5]; results in the following output:

OK :-)
0

The in-memory representation of myString would look like this:

            --- --- --- --- ---
myString:  | 1 | 0 | 2 | 3 |\0 |
            --- --- --- --- ---

i.e. char arrays are terminated by a null character '\0', for which you forgot to allocate memory.

In your code, if you want to store int avg_adc = 1023;, you should account for the one extra char and define the array as:

char myString[5];
Ziezi
  • 6,375
  • 3
  • 39
  • 49
-2
#include <stdio.h>

main()
{
        int avg_adc = 1023;
        char myString[4];
        sprintf(myString, "%d", avg_adc);
        printf("%s",myString); //you forgot this..
}
lucifer
  • 175
  • 14