Concatenate two strings

Hello!
Can anyone explain line 28 for me? I was thinking *a would be replaced by *b, but it actually appends *a to *b. I know it is related to pointer address, but could not figure it out by myself. Thanks a lot!

  1 //Concatenate two strings
  2
  3 #include<stdio.h>
  4 char *stradd (char *, char *);
  5
  6 int main()
  7 {
  8   char a[] = "abcdefg";
  9   char b[] = "GHIJKLM";
 10   char *c;
 11   printf ("a: %s\n", a);
 12   printf ("b: %s\n", b);
 13   c = stradd (a, b);
 14   printf("c: %s\n", c);
 15 }
 16
 17 char *stradd (char *a, char *b)
 18 {
 19   char *p;
 20   p = a;
 21   while (*a != '\0')
 22     {
 23       a++;
 24       printf("%p\n", a);
 25     }
 26   while (*b != '\0')
 27     {
 28       *a = *b;
 29      // printf("+++%p\n", a);
 30       b++;
 31      // printf("%p\n", b);
 32       a++;
 33      // printf("append-%p\n", a);
 34     }
 35   return p;
 36
 37 }

First off, you're writing beyond the bounds of the array, which is a bad thing. You should give a[] room to have stuff added.

char a[256] = "abcdefg";
char b[256] = "GHIJKLM";

Second off, look what the function does:

char *stradd (char *a, char *b)
{
        char *p;
        p = a;

        // Before the loop, A points to the beginning of the string.

        while (*a != '\0') // Loop until you hit the NULL terminator
        {
                a++;
                printf("%p\n", a);
        }

        // A now points to the end of the string.  Writing to the end
        // will add to the end.
1 Like

Thanks!
Got the part for a[256] , but not the stradd() function. I thought to use a = b , why shouldn't I?
I should have used *ptr1 and *ptr2 for the stradd() function to avoid confusion.

Consider it like this:

char arraya[64]="abcdefg";
char arrayb[64]="qwerty";

int a=0;
int b=5;

printf("%c\n", arraya[a]);
printf("%c\n", arrayb);

// Altering a does not alter arraya, just a!
a=b;

'char *' is like that variable 'a' up there. It doesn't tell you anything but where memory is.

The * operator dereferences it, (*a) in your code is like arraya[a] in my example.

The operator also dereferences it, like a[2] in your code would be like arraya[a+2] in my example.

Now, imagine that all memory in your process is all one great big array, so that 'a' and 'b' are simply different locations in the same big block. Altering those numbers doesn't change the memory they refer to.

1 Like

Definitely I did not catch the basic work of pointer in C. I am falling into the same pitfall of C most people did, but I want get out as soon as possible. Needs more reading.
Thanks a lot!

This has helped me with pointers and pointers arithmetic: Chapter 10: Pointers but i can't say i have mastered it yet, au contraire. You probably know that there is a stdlib function called "strcat" ?