Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of assigning the size of a string?

Tags:

c

For an instance if I store ABCDE from scanf function, the later printf function gives me ABCDE as output. So what is the point of assigning the size of the string(Here 4).

#include <stdio.h>

int main() { 

    int c[4];

    printf("Enter your name:");
    scanf("%s",c);
    printf("Your Name is:%s",c);
    
    return 0;
}
like image 692
Yogesh Singh Rawat Avatar asked Dec 07 '25 02:12

Yogesh Singh Rawat


1 Answers

I'll start with, don't use int array to store strings!

int c[4] allocates an array of 4 integers. An int is typically 4 bytes, so usually this would be 16 bytes (but might be 8 or 32 or something else on some platforms).

Then, you use this allocation first to read characters with scanf. If you enter ABCDE, it uses up 6 characters (there is an extra 0 byte at the end of the string marking the end, which needs space too), which happens to fit into the memory reserved for array of 4 integers. Now you could be really unlucky and have a platform where int has a so called "trap representation", which would cause your program to crash. But, if you are not writing the code for some very exotic device, there won't be. Now it just so happens, that this code is going to work, for the same reason memcpy is going to work: char type is special in C, and allows copying bytes to and from different types.

Same special treatment happens, when you print the int[4] array with printf using %s format. It works, because char is special.

This also demonstrates how very unsafe scanf and printf are. They happily accept c you give them, and assume it is a char array with valid size and data.

But, don't do this. If you want to store a string, use char array. Correct code for this would be:

#include <stdio.h>

int main() { 

    char c[16]; // fits 15 characters plus terminating 0

    printf("Enter your name:");
    int items = scanf("%15s",c); // note: added maximum characters
    // scanf returns number of items read successfully, *always* check that!
    if (items != 1) {
        return 1; // exit with error, maybe add printing error message
    }
    printf("Your Name is: %s\n",c); // note added newline, just as an example
    return 0;
}
like image 70
hyde Avatar answered Dec 08 '25 15:12

hyde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!