Breedly
Breedly

Reputation: 14226

Issue passing a user inputted string to a function that requires a constant char*

char hostS[32];
printf("Enter host name: ");
bzero(hostS, 32);
fgets(hostS, 32, stdin);
const char* temp = hostS;
host = gethostbyname(temp);

So this here is the problem I'm having. gethostbyname() a depreciated function requires a const char*, but I want it to use user input. I've tried just putting the string directly into the function and it works. I.E. gethostbyname("localhost");.

As it stands now when I do the user input this way I get a seg fault.

How can I get my cake and eat it too?

Upvotes: 0

Views: 85

Answers (1)

unwind
unwind

Reputation: 399871

You should just pass the array directly. A function taking a const pointer just means that for that function, the argument will be a constant pointer. It doesn't say anything about if the data is const or not const at the point the call is made.

That said, it sounds strange that the code as posted should crash.

Do note that fgets() will keep the newline/linefeed character(s) from the input, which is probably not what gethostbyname() expects to see.

Upvotes: 3

Related Questions