Array and Strings in C Programming

0 21

Array in C programming

Simply i understand, array is a variable that can hold a series of elements in a fixed size of memory. We need to tell the compiler that how many elements will have Whenever we want to declare an array.

 

The same way as variable we can declare an array but only the difference is adding [SIZE] at end of variable name. Consider the following example:

 

We should not keep an array empty. Because an empty array can hold anything. Anyway, Here is the example of initialized array:

The size is specified in [ ] and the elements are initialized in { }. And it is very important to remember C programming array index start with 0. For example if we want to print 3(Element) of numbers array then the index ID would be 2, And if 12 then the index is 11 .

 

I think below simple example is enough to understand that how an array works in C programming:

 

 

String in C programming

C language store string as array characters that terminated by ‘0\’ Null byte. Without terminating with null byte the characters set is not a string. Let’s see an example:

In this code we made the string manually and it is really a bad way. But this is how in C programming build the string(A set of Characters that is terminated with null byte).

There are few way to define string in C programming . Mostly used methods are :

  1. Using string Constant.
  2. Using Array of chars.
  3. Using pointer.

Whatever way we use to define a string , the string is terminated with ‘\0’. Whenever the Chars are enclosed with double quote ” “ ,  it is called String constant. In string constant the null byte added by compiler automatically.

Let’s see the last example:

Basically, i prefer to let the compiler to determine the array size when i need to define an string array.

Hopefully, this example is a clear example that how string works in C programming. If you have more good explanation , please share so that i can learn more 🙂 .

Leave a comment