Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As others have mentioned,</p> <pre><code>char *s = "hello ppl."; </code></pre> <p>points to read-only memory because it is a string literal. It should be </p> <pre><code>char s[] = "hello ppl."; </code></pre> <p>which creates an array in read-write memory and copies the string into it.</p> <p>Ignoring non-ASCII character sets, the problem can be solved most efficiently like this:</p> <pre><code>void Convert(char *s) { for(char *sp = s; *sp; sp++) if(*sp &gt;= 'a' &amp;&amp; *sp &lt;= 'z') *sp = (*sp - 'a' + 2) % 26 + 'a'; } </code></pre> <p>If you're dealing with EBCDIC or any other charset that doesn't have contiguous alphabetic characters, you can use a map:</p> <pre><code>char *from = "abcdefghijklmnopqrstuvwxyz"; char *to = "cdefghijklmnopqrstuvwxyzab"; char map[CHAR_MAX+1]; void Initialize() { for(int i=0; from[i]; i++) map[from[i]] = to[i]; } void Convert(char *s) { for(char *sp = s; *sp; sp++) if(map[*sp]) *sp = map[*sp]; } </code></pre> <p>The compiler will optimize each of these to nearly optimal assembly language.</p> <p><strong>Update</strong> In the original problem there was no separate Initialize() call, so I optimized the code to make "Initialize(); Convert(s);" as fast as possible. If you are able to call Initialize() ahead of time and only care about how fast "Convert(s);" runs, the optimal code will fill the array first, like this:</p> <pre><code>char *from = "abcdefghijklmnopqrstuvwxyz"; char *to = "cdefghijklmnopqrstuvwxyzab"; char map[CHAR_MAX+1]; void Initialize() { int i; for(i=0; i&lt;=CHAR_MAX; i++) // New code here fills the array map[i] = i; for(i=0; from[i]; i++) map[from[i]] = to[i]; } void Convert(char *s) { for(char *sp = s; *sp; sp++) // 'if' removed *sp = map[*sp]; } </code></pre> <p>This modified code is 375% slower if you are calling "Initialize(); Convert(s);", but it is 3% faster if you have already called Initialize() and you are only timing "Convert(s);".</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. 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