我想知道當我們有 s1 > s2 時比較什么以及結果是什么(例如,當我們比較字符時,比較它們的 ASCII 對應代碼)。我讀到通過這個操作比較了 s1 和 s2 的第一個字符,但是如果我嘗試與 s1[0] > s2[0] 進行比較,結果是不同的,那么它不可能是那樣。
uj5u.com熱心網友回復:
比較==意味著檢查指標是否指向同一個物件,所以這個:
char s1[] = "foo";
char s2[] = "foo";
if(s1 == s2)
puts("Same object");
else
puts("Different object");
將列印“不同的物件”。
<并>使得完全沒有意義,除非指標指向同一個物件。例如,你可以這樣做:
char s[] = "asdfasdf";
char *p1 = &s[3], *p2 = &s[6];
if(p1 < p2)
// Code
uj5u.com熱心網友回復:
如果您有字符陣列,例如
char s1[] = "Hello";
char s2[] = "Hello";
然后在像這樣的 if 陳述句中
if ( s1 == s2 ) { /*,,,*/ }
字符陣列被隱式轉換為指向它們的第一個元素的指標。
所以上面的陳述句等價于
if ( &s1[0] == &s2[0] ) { /*,,,*/ }
由于陣列占用不同程度的記憶體,因此這種比較的結果將始終等于邏輯假。
如果要比較存盤在陣列中的字串,則需要使用標strcmp頭中宣告的標準字串函式<string.h>。
例如
#include <string.h>
#include <stdio.h>
//...
if ( strcmp( s1, s2 ) == 0 )
{
puts( "The strings are equal." );
}
else if ( strcmp( s1, s2 ) < 0 )
{
puts( "The first string is less than the second string." );
}
else
{
puts( "The first string is greater than the second string." );
}
uj5u.com熱心網友回復:
您可以使用以下可能被視為輕微濫用前處理器的宏。
#define STROP(a, OP, b) (strcmp(a, b) OP 0)
示例用法:
STROP(s1, >=, s2) // expands to `strcmp(s1,s2) >= 0`
STROP(s1, ==, s2) // expands to `strcmp(s1, s2) == 0`
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/335224.html
下一篇:代碼列印陣列值的地址而不是值?
