Nelson Rodriguez logo
Published on

Don't get messed up with arrays of arrays in C

Authors
  • avatar
    Name
    Nelson Rodriguez
    Twitter

When dealing with arrays of arrays in C, things can get a bit confusing. Let's break it down with a simple example to clarify how they work.

Array

  • What is going to be a ?
    • 🤔 An array with 3 elements
    • 🥷 Ok, that is a[3]
  • And, what data types are its elements?
    • 🤔 The array will contain shorts
    • 🥷 Ok, that is short a[3]
  • And what are those values?
    • 🤔 The values are 13, 43, 73
    • 🥷 Ok, then the final expression is short a[3] = {13, 43, 73}
  • Conclusion: a is an array of 3 shorts.
short a[3] = {13, 43, 73}; // a[3] is an array of shorts; a is a pointer to a short

Array of arrays

  • What is going to be t ?
    • 🤔 An array with 2 elements
    • 🥷 Ok, that is t[2]
  • And, what data types are its elements?
    • 🤔 The elements are pointers (or addresses) to shorts.
    • 🥷 Ok, that is short * t[2]
  • And, what are the values of the elements?
    • 🤔 The values are the arrays a and b
    • 🥷 Ok, that is short * t[2] = {a, b};
  • Conclusion: t is an array of 2 pointers to shorts.
short a[3] = {13, 43, 73}; // a[3] is an array of shorts, a is a pointer to a short
short b[2] = {12, 32}; // b[2] is an array of shorts, b is a pointer to a short
short * t[2] = {a, b}; // t[2] is an array of arrays(pointers to shorts), t is a pointer to an array of shorts (a pointer to a short)

Pointer to a variable

  • What is going to be Pa ?
    • 🤔 A pointer (address)
    • 🥷 Ok, that is * Pa
  • And, what is it pointing to, a variable or an array?
    • 🤔 It's pointing to a variable a
    • 🥷 Ok, that is * Pa = &a
  • And, what data type contains a ?
    • 🤔 It contains an integer
    • That is int * Pa = &a
  • Conclusion: Pa is a pointer to an integer.
int a = 10; // an integer variable
int * Pa = &a; // a pointer to an integer variable

Pointer to an array (another pointer)

  • What is going to be Pt ?
    • 🤔 A pointer
    • 🥷 Ok, that is * Pt
  • And, what is it pointing to, a variable or an array?
    • 🤔 It's pointing to an array t
    • 🥷 Ok, that is * Pt = t
  • And, what data type are the elements contained by t ?
    • 🤔 It contains arrays of shorts (i.e., pointers to short)
    • 🥷 Ok, that is short * * Pt = t;
  • In conclusion: Pt is a pointer to pointers to shorts
short a[3] = {13, 43, 73}; // a[3] is an array of shorts, a is a pointer to a short
short b = {12, 32}; // array of shorts, b is a pointer to a short
short * t[2] = {a, b}; // array of pointers to shorts
short * * Pt = t; // pointer to an array of pointers to shorts