Question regarding array

0 digvijay Jadeja · July 29, 2015
when u put in the no of bytes in command char name[16] = "Digvijay Jadeja";  what happens if u put the total bytes less or more then actually required???

Post a Reply

Replies

Oldest  Newest  Rating
0 Franz Schmidt · July 29, 2015
char name[16] = "Digvijay Jadeja"; //Your string is 15 characters long

This is a nice way to define the value of a string but i would recommand to use this instead:


char name[] = "Whatever...";


This will autosize your array for you so you don't need to think about the size of it.
But if you really need to make the string a spezific length you also can use your solution.

To your questions:
If the string you write after the declaration is smaller or equal to the size of the array it will fit in and after the binary zero ('\0') it will have some undefined space which you can use later on in your programm if you want.

But if your array is smaller than your string you will get an array overflow and this is an undefined stadium of your programm. You can't say if it will work or not depends on where your compiler saves the data on your computer. 
It may could harm another program or your harddrive or if you are lucky it may work.

Whatever always check the length of your array and compare it with the length of your string if it would fit in and always remember the '\0' it will need a space in your array as well.
0 digvijay Jadeja · July 29, 2015
so it will actually occupy 16 according by even counting the string terminator rit bcoz u wrote it will count only 15 .
0 digvijay Jadeja · July 29, 2015
thnks
0 Franz Schmidt · July 31, 2015
Yeah you'r right :D
  • 1

C

107,120 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator