Why does this print the wrong part of the string?

1577 views c

void buggy_substring(char *input, size_t pos, size_t len)
 input += pos;
 input[len] = '\0';

int main(int argc, char *argv[])
 char name[16];
 strcpy(name, "Tessier-Lavigne");
 buggy_substring(name, 3, 2);
 printf("%s\n", name);
 return 0;

Why does this print "Tessi" instead of 'si'? Is this an issue of mingling size_t with char?

answered question

2 Answers


C is a pass-by-value language. Your input += pos in your substring function doesn't change anything about name in main.

posted this

You change the start position only on the function. However, when printing you are still passing the original head of the string to printf.

Try passing name+3 to printf . If course you should he using library string manipulation functions for more serious code and don't try to reinvent the wheel

posted this

Have an answer?


Please login first before posting an answer.