2013-04-02 80 views
0

行,所以我在C我proggramming並要檢查,如果字符串起初我這個改變,以便:檢查字符串是否改變

if(strcmp (ax,result)!=0){ 
    result=ax; 
     xil_printf(result); 
     xil_printf("detected"); 
} 
    } 

它檢測到只有1次,後來我想通了,我做這兩個指針是相等的,那麼即使斧頭的變化因此會發生,因爲它們現在都指向相同的東西,但我並不希望我只想改變結果的數據等於斧頭的屬性因爲字符串ax將在代碼中稍後改變,所以我可以檢測它何時發生。 所以我想這:

if(strcmp (ax,result)!=0){ 
    *result=*ax; 
     xil_printf(result); 
     xil_printf("detected"); 
} 
    } 

,並推出了錯誤,反正怎麼做我想做的事情,我做的結果requal的數據砍掉,但他們都沒有指向同一件事: 所以如果

ax-->"hello" adrress: 232 
result-->"frog" adrress: 415 

我發現他們是diffren那麼我這樣做:

ax-->"hello" adrress: 232 
result-->"hello" adrress: 415 

但不喜歡這樣! :

ax-->"hello" adrress: 232 
result-->"hello" adrress: 232 <--(they point at same thing which happens when i say result=ax) 

那麼有什麼想法?

+0

這是真的很難要理解你要問什麼,但在C中,字符串比較不是用「==」完成的,而是通過(strcmp(str1,str2)== 0) – SecurityMatt

+4

如果需要分配空間,則使用'strcpy()'。如果您分配了空間,請不要忘記在完成使用後釋放空間。 – pmg

+0

所以strcpy()將數據從指針複製到指針,但不會改變他們指向的內存地址? –

回答

1

你需要做的strcpy(result, ax);

唯一的事情是,你需要確保結果具有足夠的空間來存儲最新的斧頭

所以你的代碼會

if(strcmp(ax,result) != 0){ // result is different from ax 
    strcpy(result, ax);  // copy ax to result 
    xil_printf(result); 
    xil_printf("detected"); 
}