Wednesday, 15 April 2015

c++ - passing char by pointer and getting a different result -


I'm using gethostname to get the name of the computer I'm working on. In my main work, I call it and UBU 24-PS-23 gets the correct name of my computer. Then I call a function and use this meetHost name and I get a different string. My main function gives gethostname 0, so it works, in my work it gives 1 so it fails. Any ideas why? Here is my code

  #include & lt; Iostream & gt; # Include & lt; Sys / unistd.h & gt; using namespace std; Int funToGetHostName (four * name, size_t lane); Int main () {Charged hostname [128]; Four hostname ceremonies [128]; Int g = gethostname (hostname, sizeof hostname); Int r = funToGetHostName (hostname function, sizeof hostnameFunction); Cout & lt; & Lt; "My hostname:% s \ n" & lt; & Lt; For host name & lt; & Lt; "" & Lt; & Lt; G & lt; & Lt; Endl; Cout & lt; & Lt; "My hostname function:% s \ n" & lt; & Lt; HostnameFunction & lt; & Lt; "" & Lt; & Lt; R; Return 0; } Int funToGetHostName (char * name, size_t len) {return gethostname (name, sizeof len); }  

  int funToGetHostName (char * name, size_t len) {return gethostname } (Name, size lanen);   

The length of the size is expected to be smaller than expected.

Instead, you want:

  returns guesthostname (name, lane);  

Because you are already in buffer length when calling your function.


No comments:

Post a Comment