2013-04-01 51 views
0

我是C新手,在確定如何做到這一點時遇到了一些麻煩。如何遍歷指向C中char數組的指針?

我需要遍歷一個字符串,並一次存儲每個字母以解密它。

所以我在做什麼:

#1。創建一個存儲字符串的地方:

char toDecrypt[] = node->string; 

#2。啓動for循環:

for(int m=0; m< strlen(toDecrypt); ++m) 

#3。存儲CHAR(稍後解密):

char i = toDecrypt[m]; 

那麼,上述有效,或者我應該使用不同的符號來正確地儲存字符?

編輯:

好吧,我想我有一個清理,所以我只是有一個跟進的問題。

如何檢查字符是否爲「\」?我的支票似乎沒有工作。

當我把

toDecrypt[m] != '\'; 

到if語句,它不工作...

+0

#2:您正在評估該字符串的長度對於'for'循環中的每次迭代,我寧願使用 for(int m = 0,int L = strlen(toDecrypt); m

+2

轉義反斜槓,'\\' '。 –

回答

1

定義你的變量char *toDecrypt = node->string;

你仍然可以使用[]符號來如果你願意,可以讀/寫。

0

這是wrongchar toDecrypt[] = node->string;

您可以用下列方法解決它:

char *toDecrypt = node->string; 

char *toDecrypt=(char*) malloc (strlen(node->string)+1); 
strcpy(toDecrypt,node->string); 
0
  • 創建一個地方來存儲字符串:

您實際上已經有了一個存放字符串的地方。 node->string存儲字符串就好了。你可以創建一個指針指向它:

char *toDecrypt = node->string; 

,或者如果你想在某處複製它可以使一個數組:

char toDecrypt[enough_space_for_the_string]; 

// or do it dynamically with: 
//  char * toDecrypt = malloc(enough_space_for_the_string); 
//  just don't forget to free() it later 

strcpy(toDecrypt, node->string); 
  • 我如何檢查,看看是否一個字符是「\」?我的支票似乎沒有工作。

反斜線在C轉義字符,所以如果你要檢查一個反斜槓,你需要使用正確的escape sequence

toDecrypt[m] != '\\';