我正在嘗試撰寫一個 C 函式,它比較字串不是指標相等而是內容相等。但我收到一個錯誤
錯誤:一元“*”的無效型別引數(有“int”)
這是我的代碼:
#include <stdio.h>
#include <stdlib.h>
int stringcompare(char * str1, char * str2, int strSize){
char * word1 = str1;
char * word2 = str2;
for (int i = 0; i < strSize; i ) {
if (*word1[i] != *word2[i]) {
printf("The strings are DIFFERENT!");
return 1;
}
}
printf("The strings are a MATCH!");
return 0;
}
int main(void){
char * str1 = "Hello World!";
char * str2 = "Hello World!";
stringcompare(str1, str2, 13);
}
uj5u.com熱心網友回復:
對于由 指向的陣列,*ptr位置i處的元素被 解除參考*(ptr i),這相當于ptr[i]和 不是*ptr[i]。
uj5u.com熱心網友回復:
這個 if 陳述句
if (*word1[i] != *word2[i]) {
不正確,因為運算式word1[i]和word2[i]的型別為char。因此,您不能對型別為 的物件應用取消參考運算子char。
你應該寫例如
if ( word1[i] != word2[i]) {
請注意,標準字串函式strcmp只有兩個引數,它回傳負值、零或正值,具體取決于第一個字串是大于第二個字串還是等于第二個字串或小于第二個字串細繩。
看來您的意思是另一個strncmp確實具有三個引數的標準字串函式..
您還需要檢查是否已經遇到零終止字符。
除此之外,函式引數應該具有限定符,const因為傳遞的字串不會在函式內更改。
可以通過以下方式宣告和定義該函式
int stringcompare( const char *s1, const char *s2, size_t n )
{
while ( n && *s1 && *s1 == *s2 )
{
s1;
s2;
--n;
}
return n == 0 ? 0 : *s1 - *s2;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/360385.html
下一篇:僅對所有操作使用指標交換結構
