What is the Difference Between Declaration of an Array and a Variable in C

«
»
Question: What is the Difference Between Declaration of an Array and a variable in C?

Answer: Let’s try to understand following declarations,

int main(void)
{
    int x;	      /* x is declared as integer */
    char initial;     /* initial is a character */
    int num[10];      /* num is an array of 10 integers */
    char msg[10];     /* msg is an array of 10 characters */
 
    return 0;
}

Let’s unravel how these declarations are internally interpreted. When we compile the program containing these statements, compiler compiles the program instruction by instruction. When it reaches the first statement,

advertisement
    int x;

it allocates a block of 4 bytes of memory for ‘x’ because it’s of type int on Linux System. It recognises this block by address of its first byte i.e. integer x is located at this address in the memory, though, we name this block as ‘x’.

When compiler reaches the next statement:

advertisement
    char initial;

it allocates just one byte of memory and recognises this as character ‘initial’. Individual variables like ‘x’, initial etc. are also called “Scalar variables”.

Now, when compiler reaches the statement:

    int num[10];

it sets aside a block of 40 bytes for 10 integers specified by subscript and creates the name ‘num’ and sets this to the beginning of the block. This declaration is also called as vector i.e. an array of 10 integers. Next statement:

advertisement
    char msg[10];

when compiled, creates an array ‘msg’ of enough size to hold 10 characters.

Remember that compiler allocates memory to a scalar variable according to its type on a given system.

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn