Rn2dy
Rn2dy

Reputation: 4190

Why passing address of pointer to a function in C

I come across the functions like strtok_s where you will need to pass a pointer to pointer argument.

strtok_r(char *restrict str, const char *restrict sep, char **restrict lasts);

The way to use it is:

char *foo;
char *str = ...;
char *delimiter = ...;
strtok_r(str, delimiter, &foo);

Wondering why pass the address of pointer foo into the function?

Upvotes: 3

Views: 796

Answers (3)

Jack
Jack

Reputation: 133567

Because strtok is not reentrant while strok_r is. This means that you can't safely call it from multiple threads. To fix this, it is necessary for the function to store its status somewhere and this can be done by passing a pointer to a pointer so that strok_r is able to modify value of the pointer passed (which is another pointer) as argument.

Upvotes: 1

aaazalea
aaazalea

Reputation: 7910

the function strtok_r(str, delimiter, &foo) puts its output into foo and needs a pointer to it in order to no just replace the (copied) input object.

Upvotes: 0

Jesus Ramos
Jesus Ramos

Reputation: 23268

It's so that strtok can resume where it left off. This version of strtok is thread safe (since it uses a pointer you supply and not the internal pointer of the other version).

It saves the address of the last token read in a char * so you need to pass a pointer to that pointer so it can change the value and return it to you.

Upvotes: 2

Related Questions