educative.io

How do you know how much space you have to assign to the string?

There is this code:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char intString[] = "1234";
    char floatString[] = "328.4";
    int myInt = atoi(intString);
    double myDouble = atof(floatString);
    printf("intString=%s, floatString=%s\n", intString, floatString);
    printf("myInt=%d, myDouble=%.1f\n\n", myInt, myDouble);

    int a = 2;
    double b = 3.14;
    char myString1[64], myString2[64];
    sprintf(myString1, "%d", a);
    sprintf(myString2, "%.2f", b);
    printf("a=%d, b=%.2f\n", a, b);
    printf("myString1=%s, myString2=%s", myString1, myString2);
    return 0;
}

The text says:
First, we have to allocate space in memory to store the string. Then we use the sprintf() built-in function to “print” the numeric type into our string.

How do I know which number to assign to the string? Why 64 in this line?
char myString1[64], myString2[64];

It depends on the size of your string. Each character takes one byte of memory. Therefore if you need to store a string with 64 characters, then you should declare a string array with a size of 64. I hope this helps.

Maida Ijaz | Developer Advocate
educative.io