Passing pointers and arrays to a C function

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
36 replies · 30K views
chroot said:
You can use the safe function strnlen (notice the N, it's strnlen, not strlen) to count the length of your string for you. You must pass it the length of the array, and it will not return a value past the end of the array, even if the array does not contain a NULL.

Interestingly enough, I couldn't find strnlen() mentioned in either of my books. How many arguments does it take? Thank you.
 
Physics news on Phys.org
I have a question about incrementing, if anyone has a moment. I as playing with a function example in an old book I have. It copies one string to another when you give it the arguments of pointers to the string to be copied to and the string to be copied from.

void StringCopy(char *to, char*from)
{
while(*from)
*to++ = *from++;
*to = '\0';
}

And it made me wonder ... it appears to me that moving the characters from "from" to "to" doesn't start until the pointer is at the second element, because it starts at to++ which is "to + 1" instead of starting at "to + 0". Yet it copies the first element over.
Also, it appears that the function is filling the string with null values after each completed copy to the new string. Why is this being done?
Thanks.
 
Math Is Hard said:
And it made me wonder ... it appears to me that moving the characters from "from" to "to" doesn't start until the pointer is at the second element, because it starts at to++ which is "to + 1" instead of starting at "to + 0". Yet it copies the first element over.
Also, it appears that the function is filling the string with null values after each completed copy to the new string. Why is this being done?
Thanks.
I rewrote the code with some formatting.
Code:
void StringCopy(char *to, char*from)
{
  while(*from)
    *to++ = *from++;
  *to = '\0';
}
As you can see, the last line in the function is executed only after the loop terminates. Also note that

*to++ = *from++;

translates to

*to = *from;
to++; from++;

Hope that helps.
 
Math is Hard,

The ++ operator when used as *from++, is a post-increment operator. The value is incremented after it is evaluated in the expression. You are confusing it with the pre-increment use, *(++from).

- Warren