Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your function could look like this:</p> <pre><code>char* sum_str(char* s1, char* s2) { int lenS1 = strlen(s1); int lenS2 = strlen(s2); char* newString = malloc((lenS1 + lenS2 + 1) * sizeof(char)); int i = 0; while(i &lt; lenS1) { newString[i] = s1[i]; i++; } while(i &lt; lenS2 + lenS1) { newString[i] = s2[i - lenS1]; i++; } newString[i] = '\0'; return newString; } </code></pre> <p>Note that this function allocates new string which means you should <code>free</code> this data when you finish with this string. Also note that terminating character (<code>'\0'</code>) is stored at the end of this char array so that <code>printf</code> can "print" it properly.</p> <p>Here's main:</p> <pre><code>int main() { char *s1, *s2, *s3; s1 = "Joe"; s2 = " Black"; s3 = sum_str(s1,s2); printf("%s\n", s3); free(s3); return 0; } </code></pre> <p>Output: <code>Joe Black</code></p> <p>Note that I have declared variables <code>s1</code>, <code>s2</code> and <code>s3</code> like this: <code>char *s1, *s2, *s3;</code>. If I write it like this: <code>char *s1, s2, s3;</code> then variables <code>s2</code> and <code>s3</code> are no longer arrays of characters but only characters.</p> <p>Also note that this program:</p> <pre><code> char *s1 = "Joe"; s1[0] = 'X'; printf("%s\n", s1); </code></pre> <p>will crash since it tries to change constant string literal <code>"Joe"</code>. <code>s1</code> is pointer to first character of this literal in this case.</p> <p>But this program will work fine and its output will be <code>Xoe</code>:</p> <pre><code> char s1[] = "Joe"; s1[0] = 'X'; printf("%s\n", s1); </code></pre> <p><code>s1</code> is an array initialized with string <code>"Joe"</code> so it's OK to change it.</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