0

I have a little code that merge strcpy array and pointer. I don't understand why the code displays "Good exam". I see that after the call to strcpy, ptr contains "lexam". So, can you explain when the value of a[] changes?

char a[50] = "Good luck!";
char b[50] = { 'i','n',' ', 't','h','e',' ','e','x','a','m','\0' };
char* ptr = a + 5; cout << *ptr;
strcpy(ptr, &b[7]); 
for (int i = 0; i < strlen(ptr); i++)
    cout << ptr[i];
cout << a;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Rony Cohen
  • 51
  • 1
  • 9
  • It is changed by `strcpy`, as expected? What does "why the code display what it display "Good exam"" mean? – Sam Varshavchik Jan 23 '21 at 21:18
  • 1
    *after the line of strcpy ptr contain "lexam"* - `ptr` is a pointer, it contains an address; that's all, Specifically it contains the address of the fifth char from base of array `a`, All `strcpy` did was modify the memory referred to by that address, and in so doing, the content of the array `a`. – WhozCraig Jan 23 '21 at 21:24

1 Answers1

2
    [0][1][2][3][4][5][6][7][8][9][10] [11]
a = [G][o][o][d][ ][l][u][c][k][!][\0]
b = [i][n][ ][t][h][e][ ][e][x][a][m]  [\0]

char* ptr = a + 5;

      [0][1][2][3][4][5]
ptr = [l][u][c][k][!][\0]

        [0][1][2][3][4] 
&b[7] = [e][x][a][m][\0]

What you are doing is replacing the content that starts in b[7]and overwriting whatever starts in ptr (that is equivalent to a + 5 or &a[5]).

Hence after strcpy you have:

      [0][1][2][3][4][5]
ptr = [e][x][a][m][\0][\0]

Note that the place where the symbol ! was present is now a \0 because &b[7] had length 4 while ptr had length 5.

vmp
  • 2,370
  • 1
  • 13
  • 17