Note that there are some explanatory texts on larger screens.

plurals
  1. PO2D Arrays and Pointers - C
    text
    copied!<p>Just trying to really get my head round Arrays and Pointers in C and the differences between them and am having some trouble with 2d arrays.</p> <p>For the normal 1D array this is what I have learned:</p> <pre><code>char arr[] = "String constant"; </code></pre> <p>creates an array of chars and the variable <code>arr</code> will always represent the memory created when it was initialized.</p> <pre><code>char *arr = "String constant"; </code></pre> <p>creates a pointer to char which is currently pointing at the first index of the char array "String constant". The pointer could point somewhere else later.</p> <pre><code>char *point_arr[] = { "one", "two","three", "four" }; </code></pre> <p>creates an array of pointers which then point to the char arrays "one, "two" etc. </p> <h3>My Question</h3> <p>If we can use both:</p> <pre><code>char *arr = "constant"; </code></pre> <p>and</p> <pre><code>char arr[] = "constant"; </code></pre> <p>then why can't I use:</p> <pre><code>char **pointer_arr = { "one", "two", "three", "four" }; </code></pre> <p>instead of</p> <pre><code>char *pointer_arr[] = { "one", "two", "three", "four" }; </code></pre> <p>If I try the <code>char **</code> thing then I get an error like "excess elements in scalar initializer". I can make the <code>char**</code> example work by specifically allocating memory using <code>calloc</code>, but as I didn't have to do this with <code>char *arr = "blah";</code>. I don't see why it is necessary and so I don't really understand the difference between:</p> <pre><code>char **arr_pointer; </code></pre> <p>and</p> <pre><code>char *arr_pointer[]; </code></pre> <p>Many thanks in advance for your advice.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload