Am I conatenating these strings correctly

My exposure to arrays and pointers are bit limited. And concatened strings even less ( it was not covered in my class so I had to use my book. ) So I know there are errors. I can not use any of C string libary functions. Thoughts?




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <stdio.h>

char *strcat385(char string1[ ], char string2[ ]) {
int i = 0;

while(str[i])

{
string1[i] = str[i];
++i;
}

++i;

while(str2[])

{

string1[i] = strign2[];

++i;
}



string1 [i] = '\0';


}

int main( ) {
  char str[50] = "CSC course 385 ",
       str2[ ] = "sections 701, 710";
  printf("The return from strcat385:\n%s\n", strcat(str, str2));
  printf("string1 is %s\nstring2 is %s\n", str, str2);

return 0;
}
str is out of the scope of your function, and your function never returns a char *.
A "string" is really just an array of char, whose last used element is null (zero). The actual memory may be larger. For example, you can declare an array of twenty characters:

char s[ 20 ];

which reserves space for the twenty characters.

┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
│ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │
└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘

You can then fill that space with strings strictly less than twenty characters long.

strcpy( s, "Hello" );

Which gives us the following (where ■ represents the null character).

┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
│ H │ e │ l │ l │ o │ ■ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │
└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘


Since there is room, you can add more characters to it:

strcat( s, " world!" );

giving

┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
│ H │ e │ l │ l │ o │ │ w │ o │ r │ l │ d │ ! │ ■ │ │ │ │ │ │ │ │
└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘


You can always change the string, so long as you don't try to access characters outside the indices 0..19.

s[ 5 ] = '?'; s[ 6 ] = 0;


┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
│ H │ e │ l │ l │ o │ ? │ ■ │ o │ r │ l │ d │ ! │ ■ │ │ │ │ │ │ │ │
└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘

This of course will display as "Hello?", since that first null terminates the string (not the available memory). Always make sure you have enough memory to do things like string concatenations.

Hope this helps.
Last edited on
Topic archived. No new replies allowed.