Note that there are some explanatory texts on larger screens.

plurals
  1. POFor (*ptr)[], why is printf("%p",(void*)ptr+1) working but not printf("%p",ptr+1)?
    primarykey
    data
    text
    <p>I just fail to understand the error in the following program.What I have done is I've assigned the address of an array of size 5 to a pointer <strong>ptr</strong> of type <code>(*)[]</code>.There is no type mismatch and it's ok as far as that goes.But then I want to print the value <strong>ptr+1</strong>.As I expected, it shows an error about unspecified bounds.But it just misses me how the same <code>ptr+1</code> works fine when I cast it to type <code>void*</code>.</p> <p>Casting is fine, but before it comes to that,how can the program calculate <code>ptr+1</code> as it simply doesn't know the bounds? How would it know whether to move 5 elements ahead, or 8 elements ahead or any elements ahead?Why doesn't <code>(void*)ptr+1</code> show the same error as <code>ptr+1</code>?</p> <p>To better highlight the whole thing, I have also used a pointer <code>ctr</code> which is explicitly declared to be of type <code>(*)[5]</code> instead of <code>(*)[]</code>. Please give me the technical reasons behind this.Thank you.</p> <pre><code>#include&lt;stdio.h&gt; int main(void) { int ar1[5]={1,5,3,8,9}; int (*ptr)[]=&amp;ar1,(*ctr)[5]=&amp;ar1; printf("%p\n",ptr+1); //ERROR about unspecified bounds printf("%p\n",(void*)ptr+1); //It's ok printf("%p\n",ctr+1); //It's ok } </code></pre> <p><strong>PSST!!</strong> The last two correct <code>printf()</code>s don't produce the same value.If I comment out the incorrect <code>printf("%p\n",ptr+1);</code> line, this is the output.</p> <p><strong>0023FF25</strong></p> <p><strong>0023FF38</strong></p> <p><code>PSST!!</code> I checked it again, int the <code>ptr+1</code> part of <code>(void*)ptr+1</code> , a <code>1</code> is simply being added to the numeric value of <code>ptr</code>.What's going on?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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