Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>When you write a "string" in your source code, it gets written directly into the executable because that value needs to be known at compile time (there are tools available to pull software apart and find all the plain text strings in them). When you write <code>char *a = "This is a string"</code>, the location of "This is a string" is in the executable, and the location a points to, is in the executable. The data in the executable image is read-only.</p> <p>What you need to do (as the other answers have pointed out) is create that memory in a location that is not read only--on the heap, or in the stack frame. If you declare a local array, then space is made on the stack for each element of that array, and the string literal (which is stored in the executable) is copied to that space in the stack.</p> <pre><code>char a[] = "This is a string"; </code></pre> <p>you can also copy that data manually by allocating some memory on the heap, and then using <code>strcpy()</code> to copy a string literal into that space.</p> <pre><code>char *a = malloc(256); strcpy(a, "This is a string"); </code></pre> <p>Whenever you allocate space using <code>malloc()</code> remember to call <code>free()</code> when you are finished with it (read: memory leak).</p> <p>Basically, you have to keep track of where your data is. Whenever you write a string in your source, that string is read only (otherwise you would be potentially changing the behavior of the executable--imagine if you wrote <code>char *a = "hello";</code> and then changed <code>a[0]</code> to <code>'c'</code>. Then somewhere else wrote <code>printf("hello");</code>. If you were allowed to change the first character of <code>"hello"</code>, and your compiler only stored it once (it should), then <code>printf("hello");</code> would output <code>cello</code>!)</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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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