I am confused between the following two ways:
char var[3][15] = {\"Hello_world!\", \"good\", \"bad\"}; // as known this is for an 2D array.
char *var[3] = {\"H
There's two types of two dimensional arrays, and you have both types there.
With the first one, it's an array of 5 char[15]
objects, which are layed out sequentially in memory. Unused bytes in the end of each "row" are (in your particular case but not always) filled with zeros. This is what most people think of when you say a "two dimensional array", but some people call it a "square" array to distinguish it from the other type. When you initialize it, the string literals are copied into the array directly.
[0][ 0] = 'H'
[0][ 1] = 'e'
...
[0][14] = '\0' (end of each row is filled with zeros)
[1][ 0] = 'G'
[1][ 1] = 'o'
...
[3][13] = '\0' (end of each row is filled with zeros)
[3][14] = '\0' (end of each row is filled with zeros)
The second one is an array of 5 char*
(pointers) which usually refers to an array of char
objects that do not have to be the same size. If they do point at arrays of char objects, this can be accessed as a two dimensional array. Since the length of each array may be a different size, this is referred to as a "jagged array". In your code, there's three "rows", the first is 13 chars long, the second is 5 chars long, and the third is 4 chars long. The first index of the array is sequential in memory, but arrays forming the "inner" index can be anywhere in memory. When you initialize it, this forms a one-dimensional array that points at the actual string literals. Together, they form a two-dimensional array.
[0] -> "Hello_world!"
[1] --------------------------------->"good"
[2] ---------------------->"bad"