Bulat M. Bulat M. - 1 year ago 70
C Question

Why some functions return the result both in return value and by writing to pointer passed?

Recently was reading man page of getcwd(3). It writes current working directory to passed buf pointer and also returns it as pointer to char.
Could you please explain why it does so(giving result using two ways)?

Answer Source

Many functions write to a specified argument buffer rather than allocating their own. (This allows the caller to decide how to allocate and manage the buffer.)

However, it is often convenient for a caller to use the result directly, such as when chaining function calls, so these functions additionally return a pointer to the same buffer that was passed in. For example:

char buf[256] = "foo";
fputs(strncat(buf, "bar", sizeof buf - 1));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download