please help with strcmp()

A

Andrej Hocevar

Hello,
I'm having problems with string comparisons.
I have data like char d1[3] = {1, 2, 3} and char d2[1][3] = {1, 2,
3}. Now if I do strcmp(d1, d2[1]), it compares only the first
character, it seems. What is the correct solution?

Thanks,
andrej
 
E

Emmanuel Delahaye

In 'comp.lang.c' said:
I'm having problems with string comparisons.
I have data like char d1[3] = {1, 2, 3} and char d2[1][3] = {1, 2,

How is {1,2,3} a string?

Remainder : "a string is an array of characters terminated by a 0".

You want (maybe)

char d1[] = {1, 2, 3, 0};

or more likely

char d1[] = {'1', '2', '3', 0};

or

char d1[] = "123";
3}. Now if I do strcmp(d1, d2[1]), it compares only the first
character, it seems. What is the correct solution?

You must be sure that the adresses passed to strcmp() points to valid
strings.
 
R

Russell Hanneken

Andrej Hocevar said:
I'm having problems with string comparisons.
I have data like char d1[3] = {1, 2, 3} and char d2[1][3] = {1, 2,
3}. Now if I do strcmp(d1, d2[1]), it compares only the first
character, it seems. What is the correct solution?

A string is a sequence of characters that ends with a null character. I
don't see any strings in your example, and I can't figure out what you mean
to do. Maybe you should be using strncmp or memcmp? In any case, the
second argument to strcmp--d2[1]--produces undefined results. There is no
d2[1]. There is only d2[0].
 
G

Gordon Burditt

I'm having problems with string comparisons.
I have data like char d1[3] = {1, 2, 3} and char d2[1][3] = {1, 2,
3}. Now if I do strcmp(d1, d2[1]), it compares only the first
character, it seems.

How did you determine this? You obviously used more code than
described above.
What is the correct solution?

A string has a '\0' terminator. The crap you are passing to
strcmp() above doesn't, so it's not a string.

Gordon L. Burditt
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top