I have this code:


Note:
[1][0] has the character "a" while [[tempr[0]][0] contains the string "ay".

if ( strcmp(&boom.ok[1][0],&boom.ok[[tempr[0]][0]) == 1)
printf("Hello");

if ( strcmp(&boom.ok[1][0],&boom.ok[[tempr[0]][0]) == 0)
printf("Hello");

None of these statement prints hello. Why?

Dani AI

Generated

Two likely causes explain why nothing printed: the value returned by the comparison function may not match the literal you tested for, and the pointers/indices you passed may not be the strings you think they are. and were on the right track about the result being sign-based and that nonzero return values are not fixed constants — rely on sign tests and verify the actual inputs instead of checking for a particular integer.

A quick, practical way to debug is to print the two C-strings and the integer result before making decisions. For example, capture the two pointers into named variables, print them, print their first bytes as unsigned values, then print the function return. That shows whether either pointer is NULL, whether strings are null-terminated, and what the comparator actually returned:

char *s1 = strings[1];
char *s2 = strings[index];
int r = strcmp(s1, s2);
printf("s1=\"%s\"\ns2=\"%s\"\nfirst bytes: %u %u\nstrcmp->%d\n",
       s1 ? s1 : "(null)", s2 ? s2 : "(null)",
       (unsigned char)(s1 ? s1[0] : 0), (unsigned char)(s2 ? s2[0] : 0),
       r);

Checklist of common pitfalls to verify:

  • Confirm the indexing/bracket usage is what you intended (the expression in the original post looks mis-bracketed).
  • Ensure strings are null-terminated and pointers valid (strcmp reads until a NUL).
  • Compile with warnings enabled (e.g., -Wall -Wextra) and fix any array/index warnings.
  • Use strncmp for prefix-limited compares or a case-insensitive function when appropriate.
    If uncertainty remains, reduce the problem to a small test program and run it under a debugger to see exact memory and return values. For the official semantics, see the strcmp man page: strcmp man page.

Recommended Answers

All 5 Replies

What if the from strcmp is -1?

What if the from strcmp is -1?

Is that possible? Am I right? The only return value of strcmp function is only 0 and 1 when the string or variable compared is not equal and equal?

Yes, it's possible.
The possible values are -1, 0, 1.
...but are actually described () as
Less than zero
Equal to zero
Greater than zero
...and serve specific purposes.

What if the from strcmp is -1?

I tried -1 in my statement and it works. Thanks a lot!!!

I think it return 0 if they are equal,
however,
return either a positive or negative value of the difference, can be -2 or 4 5 anything.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.