Home > Software design >  What is the point of assigning the size of a string?
What is the point of assigning the size of a string?

Time:10-06

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;
}

CodePudding user response:

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("s",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;
}

CodePudding user response:

The size of an array must be defined while declaring a C String variable because it is used to calculate how many characters are going to be stored inside the string variable and thus how much memory will be reserved for your string. If you exceed that amount the result is undefined behavior.

CodePudding user response:

In C language the last of the string is '\0'. If you print with the below function, you can see the last character of the string.

scanf("%s", c); add the last character, '\0'. So, if you use another function, getc, getch .., you should consider adding the laster character by yourself.

#include<stdio.h>                          
#include<string.h>                         
int main(){                                
  char c[4];                               
  char *p;                                 
  int len;                                 
  printf("Enter your name:");              
  scanf("%s", c);                          
  len = sizeof(c);                         
  printf("Your Name is:%s (%d)\n", c, len);
  p = c;                                   
  do {                                     
   printf("%x\n", *(p  ));                 
  } while((len--) 1);                      
  return 0;                                
}       
Enter your name:1234
Your Name is:1234 (4)
31
32
33
34
0        --> last character added by scanf("%s);
ffffffae --> garbage

CodePudding user response:

You have used int c , not char c . In C, a char is only 1 byte long, while a int is 4 bytes. That's why you didn't face any issues.

CodePudding user response:

(Simplifying a fair amount)

When you initialize that array of length 4, C goes and finds a free spot in memory that has enough consecutive space to store 4 integers. But if you try to set c[4] to something, C will write that thing in the memory just after your array. Who knows what’s there? That might not be free, so you might be overwriting something important (generally bad). Also, if you do some stuff, and then come back, something else might’ve used that memory slot (properly) and overwritten your data, replacing it with bizarre, unrelated, and useless (to you) data.

  •  Tags:  
  • c
  • Related