0

I have a pointer with type const char* FunctionName , How can I put that into a payload of type char payload[100] without any warning or errors? Also the payload[0] is filled with character value already, so the space starting from payload[1]

update:

I tried like this `strcpy((&payload[1]),FunctionName); is working now.

But Ihave one more question, how can accomodate the pointer(FunctionName) into the payload[1] ratherthan copying the entire string? through any assignment statement?

/R

1
  • what do you have so far? Commented Sep 28, 2011 at 9:06

1 Answer 1

3
strncpy(&payload[1], FunctionName, 98);
payload[99] = '\0';

should be safe in the case that FunctionName has more than 98 characters before the NULL terminator.

Sign up to request clarification or add additional context in comments.

12 Comments

what happens if FunctionName has less than 98 characters? I mean to say where should the NULL terminator be placed?
strncpy will pad the buffer with NULLs up to 98 if FunctionName is shorter than that, so you don't need to do anything different.
Great. It worked.. Don't you think, if the padding is done automatically, then the payload[99] = '\0'; statement isn't required?
No, the last line is required if the FunctionName has >= 98 characters. Rather than performing an expensive strlen() on FunctionName first, just append the NULL. It's true it's not needed if FunctionName is always less than 98 characters but this is just good defensive coding practice. If you leave it out, someone will inevitably come along and call your code with a FunctionName longer than you were expecting some time in the future.
@Renjith G: you need to use &payload[1] (the address of element 1 of payload) as the first argument - you are using the content of element 1 of payload with your statement. But strcpy (rather than strncpy) is not safe as I have explained.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.