tags:

views:

398

answers:

4

Hi

I am using strcmp as shown below.

I am debugging the values and which are coming same but still not getting that condition true.

const char opcode_read[2] = {'0', '1'};

rc = recvfrom(s, blk_receive_full, sizeof (blk_receive_full), 0,(struct sockaddr FAR *)&sin, &fromlength);

if(rc == -1){
 printf("failed: recvfrom, \n No data received \n failed code: %d\n",WSAGetLastError());
 cleanup();
 exit(1);
}

memcpy(blk_receive_opcode, &blk_receive_full, 2);
if (strcmp(blk_receive_opcode, opcode_data) == 0) {
}
+3  A: 

opcode_read is not a string. There is no NUL termination. Change its size to 3, so you pick up a NUL in the third position.

const char opcode_read[3] = {'0', '1'};

An alternative would be to use memcmp instead of strcmp so you don't have to worry about the pesky NUL terminator.

The recvfrom call is a bit scary too. If I recall my TCPIP correctly. There is no guarantee that the function will return 2 bytes in one call. It may return one byte, in the first call, and the second byte in the second call.

EvilTeach
blk_receive_opcode's not null-terminated either, and since the lengths are fixed he might as well use `memcmp`
bdonlan
+1 for the recvfrom caveat though!
bdonlan
A better alternative is to write `const char opcode_read[] = "01";` but that may just be me.
Chris Lutz
Probably depends whether or not data being trasmitted is intended to be interpreted as a single string (e.g. `"hello"`) or an "array of chars" (e.g. `{ 'T', 'F', 'T' }` as an array of three "boolean" values). The code is identical in either case (as long as you remember the latter example does not add the null terminator)
GRB
@bdonlan ya, i should have caught the other one wasn't NUL terminate either.@chris that is a style preference. I was going with the style that the questioner had.@GRB i agree it depends on the interpretation of the data. the questioner seemed interested in strings, so i shaped my answer that way.
EvilTeach
+3  A: 

You might want to try memcmp instead. strcmp is for null terminated strings.

D.Shawley
+3  A: 

From what I can tell, you aren't comparing two strings as they aren't null-terminated. You may want to use memcmp() instead:

if (memcmp(blk_receive_opcode, opcode_data, 2) == 0) {
}
yjerem
A: 

i have program phonebook,i write program with file and struct,i compare aname with name in file ,how can i do?(with c++)

maryam