2

In server.c in pset6, there is a line of code where a string is "subtracted" from a string. I tried to find out what this operation does by writing a simple program :

char* needle = "needle";
char* haystack = "haystack";
int num = haystack - needle;
printf("%d\n",num);

The program printed out the number 7 which after several tries with different strings, is apparently the number of chars in the string needle including \0. For some reason changing the string haystack doesn't affect the result. And replacing the minus operator - with the plus operator + results in an error during compilation. Why is this so? How does this operation work?

1

After going through some more code in server.c, I realized that "subtraction" of string must be for finding how much distance is between the addresses for both strings in number of bytes.
Since needle is declared first before haystack, haystack is right after needle in memory.
Hence, the distance between the first letter of needle and haystack is equal to the size of needle.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .