A Quick Note on Array

int a[] = {1, 2, 3};
  1. You get a array name, a, and three objects, a[0], a[1] and a[2]
  2. With a few exceptions, you can almost always use a as a const pointer (so that you cannot use it like a lvalue and cannot assign anything to it).
  3. Actually, according to K&R, when evaluating a[i], C will convert the expression to *(a + i)
  4. Therefore, you can almost think of int a[] as another way to do what int* const a; will do, and both {1, 2, 3} and “hello” use the address of their initial element as their value
  5. According to K&R, Section 4.10, for external, static and automatic variables, elements without a matching initializer will be zero, does that means int a[n]; almost equals int* const a = the address of the first of the n newly created consecutive zeros; while int a[] = {1, 2, 3}; almost equals int* const a = the address of the first of the three consecutive integer objects that have just been created based on the initializers? (while char* str = “hello”; uses the string constant directly and therefore you should not modify its content using pointers like *(str + 1) = ‘p’;, which leads to undefined results)
  6. That’s why you can pass a to a function that asks for a pointer like void func(int* arr); and that’s also why void func(int* arr); and void func(int arr[]); are equivalent in this case
  7. On the other hand, you can use the objects in this array just the way you will use any other ordinary variables, e.g., you may get the address of an object by using the & operator like &a[2] and you may easily assign another value to this object a[2] = 777;

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store