title: Passing const char * to a C function
body: <p>For the below <a href="https://users.cs.cf.ac.uk/Dave.Marshall/C/node8.html#SECTION00840000000000000000" rel="nofollow">question</a>,</p>
  
  <blockquote>
    <p>Write a function <code>replace</code> which takes a pointer to a string as a parameter, which replaces all spaces in that string by minus signs, and delivers the number of spaces it replaced.</p>
    
    <p>Thus</p>
  
  <pre><code>   char *cat = "The cat sat";
     n = replace( cat );
  </code></pre>
    
    <p>should set</p>
  
  <pre><code>    cat to "The-cat-sat"
  </code></pre>
    
    <p>and</p>
  
  <pre><code>   n to 2.
  </code></pre>
  </blockquote>
  
  <hr>
  
  <p>In the above problem, <code>char *cat="That cat sat"</code> is nothing but <code>const char *cat="That cat sat"</code></p>
  
  <p>Here is my non-working code for this problem,</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  int replace(char[]);
  int main(void){
    const char *cat = "The cat sat";
    int n = replace((char[])cat);
    printf("\n Now the output is: \"%s\"", cat);
    printf("n is %d", n);
  }
  
  int replace(char cat[]){
    int count =0;
    for(int i =0; cat[i] != '\0'; i++){
      if(cat[i] == ' ') {
        cat[i] = '-';
        count++;
      }
    }
    return count;
  }
  </code></pre>
  
  <hr>
  
  <p>To analyse this code,</p>
  
  <p><code>const char *cat</code> is pointing to a buffer(<code>The cat sat</code>) that cannot be modified.</p>
  
  <p>So, am casting(<code>(char[])</code>) to make <code>cat</code> a (non-const)modifiable buffer, before calling <code>replace((char[])cat)</code>. Because, C is loosely typed</p>
  
  <p>But the program still segments at <code>cat[i]='-'</code></p>
  
  <p>How do I understand this problem?</p>