CS Student CS Student - 1 month ago 9
C Question

Null byte and arrays in C

If I declare a char array of say 10 chars like so...

char letters[10];


am I creating a set of memory locations that are represented as chars from index 0-9 then the 10th index is the null byte?

if so does that mean I'm really creating 11 locations in memory for the array (0 to 10) with the last element being the null byte or do I have 10 locations in memory (0 to 9) then C adds the null byte at a new position (so the array is 1 byte longer than I declared)?

Thanks

Answer

Seems like you are confused with arrays and strings.
When you declare

char letters[10] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};  

then it reserves only 10 contiguous bytes in a memory location.

  2000  2001  2002  2003  2004  2005  2006  2007  2008  2009  //memory addresses. I assumed it is to be starting from 200 for simplification. 
 +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
 |     |     |     |     |     |     |     |     |     |     |
 | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' |
 |     |     |     |     |     |     |     |     |     |     |
 +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+

In C indexing starts from 0. You can access your allocated memory location from letters[0] to letters[9]. Accessing the location letters[10] will invoke undefined behavior. But when you declare like this

char *letters = "0123456789";  

or

char letters[11] = 0123456789"; 

then there are 11 bytes of space are allocated in memory; 10 for 0123456789 and one for \0 (NUL character).

 2000  2001  2002  2003  2004  2005  2006  2007  2008  2009  2010 //memory addresses. I assumed it is to be starting from 2000 for simplification. 
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+
|     |     |     |     |     |     |     |     |     |     |       |
| '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '\0'  |
|     |     |     |     |     |     |     |     |     |     |       |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+  
                                                                ^
                                                                | NUL character   

Take another example

#include <stdio.h>

int main(){
   char arr[11];
   scanf("%s", arr);
   printf("%s", arr);

   return 0;
} 

Input:

asdf  

Output:

asdf

Now have a look on memory location

 +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+
 |     |     |     |     |     |     |     |     |     |     |       |
 | 'a' | 's' | 'd' | 'f' |'\0' |     |     |     |     |     |       |
 |     |     |     |     |     |     |     |     |     |     |       |
 +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+  
Comments