2011-10-06 70 views
-2

我存儲「你好」世界字符數組分配characteres成字符指針,C語言程序設計,指針

char a[100],*p; 
p=a; 

我找到字符串的長度,使用指針的話,我應該如何找到字符串的位置。 程序

char a[100],*p; 
int lenth; 
printf("Enter the string:"); 
gets(a); 
p=a; 

while(*p) 
{ 
    length++; 
    p++ 
} 
printf("Length=%d",length); 
+7

定義「字符串的位置」,假設你想要其他的東西,「它從一個[0]開始到一個[長度](包括nul終止符)」。 – DwB

+0

你有'p = aa;'..那是正確的嗎? – 2011-10-06 15:56:03

+0

你是什麼意思的字符串的位置? –

回答

1

我認爲,如果你想獲得你只需要使用strlen(一)以獲取長度字符串的長度。

,但如果你想模仿的strlen你可以寫這樣的事情

size_t length = 0; 
for (char* p = a; p < a + sizeof(a) && *p; ++p, ++length); 
+0

我得到了字符串的長度,現在我需要找到特定字符形式給定字符串 – vinothvetrivel

+0

的位置而不使用** strlen()** function – vinothvetrivel

0

做搜索,對結果保存到地址,所以p - 一個是指數。

char target = 'e'; 
for (p = a; *p && *p != target; ++p) {}; 
int result = p - a; 
// if target doesn't exists result === Length