Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

char struct and comparison 1

Status
Not open for further replies.

simanek

Programmer
Joined
Jan 19, 2001
Messages
137
Location
US
hi all,

I'm using the getpwnam method of the pwd library and in it, it has a passwd struct. A member of this struct is called char *pw_shell. When I call getpwnam("simanek") I am returned a passwd struct that i call pw. Now, I'm trying to see if my shell is /bin/ksh (which it is) but for some reason, I cannot compare them. The following is my 'if' statement for comparison.

if(pw->pw_shell == "/bin/ksh")

this fails no matter what i do. However, when I do printf(pw->pw_shell) "/bin/ksh" (no quotes) is printed to my console. Any ideas?
Thanks. Mike
~~~~
simanek@uiuc.edu
"It's a Swingline!"
~~~~
 
Try using this instead:

if (!strcmp(pw->pw_shell, "/bin/ksh"))
{
}

;-)
 
Just for further reference, the comparison was failing because it was comparing pointer values, not the actual char values. pw->pw_shell gives you a pointer. If you wanted to do the actual comparison by yourself you would need to dereference the pointer and check each char, eg:
Code:
char *pt="/bin/ksh";
bool comp=true;
for(int i=0;i<8&&comp;i++){
  if(*(pt+i)==(pw->pw_shell)[i]){
    comp=false;
  }
}
if(comp){
  ...code...
}
This is a little redundant and unecessary but helps show why your comparison fails I hope. Obviously there is the need for more error checking, such as the event that your string is the same but longer than the string to check:
Code:
if(comp&&*(pw->pw_shell+8)!=NULL){
  comp=false;
}
In order for your comparison to return true the pointers would both have to be pointing to the exact same char in memory. Fun with pointers! good luck MYenigmaSELF
myenigmaself@yahoo.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top