Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>I am wondering why this line of code is only printing the first character <code>H</code> of a literal character array <code>string</code> and not the full string <code>"Hello"</code> </p> </blockquote> <pre><code>char *myCharPointer = "Hello"; </code></pre> <p><code>myCharPointer</code> is pointer to the first character of the string literal <code>Hello</code>, i.e, <code>H</code>. Buy using <code>*</code> operator in <code>*myCharPointer</code> you are dereferencing the pointer <code>myCharPointer</code> which will give the value stored at the location pointed by <code>myCharPointer</code> which is <code>H</code>. That's why you are getting <code>H</code>. </p> <blockquote> <p>I also tried changing the format specifier to %s, but the program crashed. </p> </blockquote> <p><code>*myCharPointer</code> is of <code>char</code> type and you need <code>%c</code> specifier to print a <code>char</code>. To print the string literal use <code>%s</code> specifier </p> <pre><code> printf("The value of myCharPointer is %s \n \n", myCharPointer); </code></pre> <p>To print the value of the address use <code>%p</code> specifier </p> <pre><code> printf("The value of myCharPointer is %p \n \n", (void *)myCharPointer); </code></pre> <p>The snippet </p> <pre><code>int myIntArray[10]; int *myIntArrayPointer; myIntArrayPointer = myIntArray; </code></pre> <p>is valid because <code>myIntArrayPointer</code> is <code>pointer to int</code> type. Array name are decays to pointer (not always) and hence <code>myIntArray</code> is also a pointer to int type and that's why <code>myIntArrayPointer = myIntArray;</code> is valid. </p> <pre><code>int myIntArray[10]; int *myIntArrayPointer; myIntArrayPointer = &amp;myIntArray; </code></pre> <p><code>&amp;myIntArray</code> is of type <code>int (*)[10]</code> i.e, pointer to array of 10 integers. As I stated above <code>myIntArrayPointer</code> is of type <code>int *</code> and hence assignment is not valid . </p> <blockquote> <p>I also tried changing the format specifier to %s, but the program crashed. </p> </blockquote>
 

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