What is the relation between the gets() function and a character array's size? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is the relation between the gets() function and a character array's size?

Code: #include <iostream> #include <stdio.h> using namespace std; char ch[5]; int main() { cout << "Size of character array before input: " << sizeof(ch) << endl; gets (ch); puts (ch); cout << "Size of character array after input: " << sizeof(ch); return 0; } And the output came to be: Size of character array before input: 5 ABC DE FGHIJKL //Input ABC DE FGHIJKL //Output Size of character array after input: 5 How can the whole input be displayed with no change in size?

18th Dec 2017, 7:28 PM
Advitiay Anand
Advitiay Anand - avatar
3 Answers
+ 3
beacause when you put char c[5] you already allocate memory for 5 characters no matter did you put something in that positions in array
18th Dec 2017, 7:37 PM
Vukan
Vukan - avatar
0
Isn't the size of 1 character supposed to be 1 byte? Hence, sizeof(ch) outputting 5 before any input. So, how is 5 bytes of storage able to hold more than 5 characters?
18th Dec 2017, 7:41 PM
Advitiay Anand
Advitiay Anand - avatar
0
So then, somehow, 5 bytes CAN store more data than merely 5 characters? That is what we conclude, right?
18th Dec 2017, 8:52 PM
Advitiay Anand
Advitiay Anand - avatar