0

I need to read IP addresses into a char array for working on it later. Since IP octets can be as big as 256, I thought it would be good to use unsigned char array to read them. This is how I intend to use it.

sprintf(buf,"%d.%d.%d.%d",ip24,ip16,ip8,ip);

But it appears that first argument of sprintf should be char* and hence it's throwing the below warning. How do I deal with it.

expected ‘char * restrict’ but argument is of type ‘unsigned char *’
3
  • why not initialize buf as a char array, big enough to handle an ip address? this way you dont need it to be unsigned: char buf[16]="255.255.255.255" Commented Apr 9, 2018 at 9:14
  • 2
    What's irrelevant is that "IP octets can be as big as 256". So what? You're rendering them as a text string, which is made up of chars. This question indicates a lack of thought about what you're doing. Commented Apr 9, 2018 at 9:23
  • You haven't shown us, but buf is obviously the wrong type. Declare it as a char * rather than an unsigned char*. And depending on the type of ip and friends, you probably want to use %u rather than %d (and octets cannot be as large as 256; the valid range is [0,255]). Commented Apr 9, 2018 at 12:15

3 Answers 3

2

The type of buf should be char* in first place. The fact that an IP octet can be as big as 256 (that is it is a unsigned char) has nothing to do with the fact that buf is an array of unsigned char.

sprint wants a char* as first argument, so give it a char:

Live Demonstration

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

Comments

2
sprintf((char*)buf,"%d.%d.%d.%d",ip24,ip16,ip8,ip);

this can avoid the warning. But why not use char* buf?

2 Comments

This answer is misleading, he just shouldn't use unsigned char* but char*.
@Jabberwocky Many times it is not up to the code maintainer to choose the datatype.
1

You need to declare buf as a char* or char buf[16] instead of unsigned char*, or cast it when using, if changing the data type of buf is a hassle.

As you rightly stated, referring to the man page for sprintf(), it indicates that it expected the first argument of the type char *str.

Comments

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.