Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Consider the code:</p> <pre><code>#include &lt;stdio.h&gt; char a1[] = "June 14"; const char *a2 = "June 14"; void function(void) { char b1[] = "June 14"; const char *b2 = "June 14"; printf("%-7s : %-7s : %-7s : %-7s\n", a1, a2, b1, b2); a1[6]++; b1[6]++; a2++; b2++; printf("%-7s : %-7s : %-7s : %-7s\n", a1, a2, b1, b2); } int main(void) { function(); function(); return(0); } </code></pre> <p>The array <code>a1</code> is allocated space and initialized as the program is loaded with the string. The pointer <code>a2</code> is allocated space for the pointer and that pointer is initialized to point to a copy of the string. I used <code>const</code> because you can't modify string literals; the value might be stored in the text segment of the program (which is non-writable).</p> <p>The array <code>b1</code> is allocated space on the stack and when the function is called, it is initialized with the string. This means, as <a href="https://stackoverflow.com/users/1322972/whozcraig">WhozCraig</a> noted in a <a href="https://stackoverflow.com/questions/18538179/comparison-of-array-and-pointer-version-in-terms-of-memory-allocation#comment27266059_18538179">comment</a>, that there must be a copy of the string somewhere that is used to initialize the array each time the function is called. The pointer <code>b2</code> is allocated space for the pointer and that pointer is initialized to point to a copy of the string. Indeed, the compiler might make <code>a2</code> and <code>b2</code> point to the same string.</p> <p>The function prints the values of the four strings; it then modifies the last digit of the number in the two arrays, and increments the two pointers to point to the next character in the string constants, and prints the four strings again. The second call to the function resets <code>b1</code> to the original string (<code>"June 14"</code>), but <code>a1</code> remains changed to <code>"June 15"</code> at the start of the second call. Similarly, <code>a2</code> remains pointing at the <code>u</code> for the first print but at the <code>n</code> for the second, while <code>b2</code> points to <code>J</code> first and <code>u</code> second. Thus the output is:</p> <pre><code>June 14 : June 14 : June 14 : June 14 June 15 : une 14 : June 15 : une 14 June 15 : une 14 : June 14 : June 14 June 16 : ne 14 : June 15 : une 14 </code></pre> <p>If there was a static array or a static pointer inside the function, they would behave analogously to the external array <code>a1</code> and pointer <code>a2</code>.</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