title: Are the elements of an array saved continuously in memory?
body: <p>I am following a programming paradigm tutorial and doing some memory related exercises. I just extracted two questions (please forget about what the codes look like, sorry it is bad code but I just want to learn the pointer stuff from it). The original codes make lsearch as generic as possible so it uses all pointers.  </p>
  
  <ol>
  <li><p>I have a question about accessing an element of an array:</p>
  
  <p>When we access the fourth element of array <code>a[]</code>, we use <code>*(a+3)</code>;
  When we access the 3rd element of string array <code>char * names[]</code>, we use <code>*(char**)((char*)names+sizeof(char*)*2)</code>.
  Do we assume the elements of an array are saved continuously in the memory?</p></li>
  <li><p>Question 2 about accessing string array element: why do we need to add <code>(char*)</code> in front of <code>names</code> (the base address), I tried not to add <code>(char*)</code> and the codes crashed with segmentation fault error. I printed the size of <code>(char*)</code>, it is 8, while <code>sizeof(names)</code> is 32. Why do we need <code>(char*)</code> here? I really think the address is 32 bits and if we cast it into 8 bits, the computer should have trouble finding the element it points to. 
  Thank you   </p></li>
  </ol>
  
  <p></p>
  
  <pre><code>#include&lt;iostream&gt;
  #include&lt;string&gt;
  #include&lt;typeinfo&gt;
  int main()
  {
          int a[5] = {1,2,3,4,5};
          std::cout &lt;&lt; *(a+3) &lt;&lt; std::endl;
  
  
          char* names[4] = {"James", "Dustin", "Rich", "Ed"};
          std::cout &lt;&lt; *(char**)((char*)names+2*sizeof(char*)) &lt;&lt; std::endl;
          //std::cout &lt;&lt; sizeof(names) &lt;&lt; " " &lt;&lt; sizeof(char*) &lt;&lt; std::endl;
  }
  </code></pre>
  
  <p>Here is the original codes from stanford 107.  </p>
  
  <pre><code>#include&lt;iostream&gt;
  #include&lt;string.h&gt;
  #include&lt;stdio.h&gt;
  using namespace std;
  
  int StrCmp(void* vp1, void* vp2)
  {
          char *s1 = *(char**)vp1;
          char *s2 = *(char**)vp2;
          if(strcmp(s1,s2)==0){
                  return 0;
          }
          return 1;
  }
  
  char ** lsearch(void *key, void* base, int size, int elemSize, int (*cmpFn)(void *, void *))
  {
          for(int i=0; i&lt;size; ++i){
                  char* addr = (char*) base + elemSize *i;
                  if (cmpFn(key, addr)==0) return (char**)addr;
          }
          return NULL;
  }
  
  int main()
  {
          char *notes[] = {"Ab", "F#", "B", "Gb", "D"};
          char* favorStr = "F#";
          char ** found = lsearch(&amp;favorStr,notes,5,sizeof(char*),StrCmp);
          if(found!=NULL) cout &lt;&lt; *(char**)found &lt;&lt; endl;
          else cout &lt;&lt; "not found" &lt;&lt; endl;
  }
  </code></pre>