Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Stack allocation</strong></p> <pre><code>char *mystring ="love is alweys better yoe"; </code></pre> <p>This creates a string literal in read-only memory, and you cannot subsequently write to it to change characters.</p> <p>You should initialise your string like this instead:</p> <pre><code>char mystring[] ="love is alweys better yoe"; </code></pre> <p>This will allocate a character array of size 26 bytes - 1 byte per character, terminated with a null character <code>\0</code>.</p> <p>Note that if you attempt to write past the end of the buffer (i.e. beyond the <code>\0</code> character), you may be invading the memory allocated for other data in your program, and this can have undesirable consequences.</p> <p><strong>Heap allocation</strong></p> <p>The previous example allocates memory on the stack, and will be free'd at the end of the current level of scope (usually the function you are in). If you want the memory to persist beyond the end of the function call, you need to allocate it on the heap like so:</p> <pre><code>int bufferSize = 26; char* mystring = malloc(bufferSize); strncpy(mystring, "love is alweys better yoe", bufferSize); </code></pre> <p>And you will need to remember to <code>free</code> this memory when you are done with it:</p> <pre><code>free(mystring); </code></pre> <p>If <code>free</code>ing from the calling function, you will need to return the <code>char*</code> pointer back to the caller, so it knows which memory location to <code>free</code>. If you don't <code>free</code> this memory, your program will leak memory.</p> <p><strong>Increasing size of string</strong></p> <p>If you need to re-size the string after allocating memory for it, you can use <code>realloc</code>:</p> <pre><code>char* mybiggerString = realloc(mystring, bufferSize + 10); strncpy(mystring, "I can fit more in this string now!", bufferSize); </code></pre>
    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. 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