What does `strcpy(x+1, SEQX)` do?

397 views Asked by At

I'm wondering what this syntax of strcpy() does in line 65 and 66:

 24 #define SEQX "TTCATA"
 25 #define SEQY "TGCTCGTA"
 61   M = strlen(SEQX);
 62   N = strlen(SEQY);
 63   x = malloc(sizeof(char) * (M+2)); /* +2: leading blank, and trailing \0 */
 64   y = malloc(sizeof(char) * (N+2));
 65   strcpy(x+1, SEQX);            /* x_1..x_M now defined; x_0 undefined */
 66   strcpy(y+1, SEQY);            /* y_1..y_N now defined; y_0 undefined */

I know it's copying SEQX and SEQY into x and y but I don't understand what does the +1 do? What's the formal name of this type of operation?

2

There are 2 answers

0
Ja͢ck On BEST ANSWER

The pointer + offset notation is used as a convenient means to reference memory locations.

In your case, the pointer is provided by malloc() after allocating sufficient heap memory, and represents an array of M + 2 elements of type char, thus the notation as used in your code represents the following address:

<x + 1 * sizeof(char)>

And this also happens to be the same as:

&x[1]

In other words, the address of x[1] (second element of x). After the strcpy() operation the memory would look like this:

[0] [1] [2] [3] [4] [5] [6] [7]
??? 'T' 'T' 'C' 'A' 'T' 'A' '\0'
^
x

In other words:

strcmp(x + 1, SEQX) == 0

Note that before practical use of x as a string, the first memory location should be defined, i.e.

x[0] = '='; // now the string holds "=TTCATA"
2
eyalm On

strcpy(x+1, SEQX); copies the SEQX into x buffer but it leaves the first byte unchanged. At the comment it says: /* +2: leading blank, and trailing \0 */. it is skipped deliberately.

This is the structure of the allocated buffer:

+---+---+---+---+---+---+---+
| x |x+1|x+2|x+3|...|   |   |
+---+---+---+---+---+---+---+