Initializing 2D char array in C

I think pictures help. Here is char newarray[5][10]. It is a single memory block consisting of an array of 10 characters, and an array of five of those. You could just clear it with a single memset call.

Here is char **array. It says array is a pointer. What is it a pointer to? a pointer to a character.

Keep in mind pointer arithmetic. If array is a pointer that happens to point to a pointer, then (*array) equals array[0], and that is the pointer that array points to.

What is array[1]? It is the second pointer in the array that array points to.

What is array[0][0]? It is the first character pointed at by the first pointer that array points to.

What is array[i][j]? It is the jth character of the ith pointer that array points to.

So how are newarray and array related?
Simple. newarray[i][j] is the jth character of the ith subarray of newarray.

So in that sense, it’s just like array, but without all the pointers underneath.

What’s the difference? Well, the disadvantage of array is you have to build it up, piece by piece. OTOH, the advantage is you can make it as big as you want when you build it up. It doesn’t have to live within a fixed size known in advance.

Clear as mud?

Leave a Comment

deneme bonusu veren sitelerbahis casinomakrobetceltabetpinbahispolobetpolobet girişpinbahis girişmakrobet girişpulibet girişmobilbahis girişkolaybet giriş