2013-09-24 13 views
5

私がしたいのは、見積もりの​​終わり(*引用符に何も入っていない)まで見積もりを繰り返すことです。私のコードは有効ですか?ポインタで作成された文字列をループする方法

char *quote = "To be or not to be, that is the question."; 
for (quote = 0; *quote != NULL; quote++){ 
*quote = tolower(*quote); 
} 
+3

'' quote = 0'は間違っています。 – Zong

+0

なぜ 'unsigned int'を使わないのですか? – Recker

答えて

11

おそらく、配列を走査する別のポインタが必要です。そうしないと、元の文字列へのアクセスが失われます。

そして、好ましくはポインタとしてNULLを使用してください。

代わりにインデックスを使用する場合を除き、0を初期値として使用しないでください(下記参照)。

Doing char *quote =は、文字列をコピーするのではなく、単にquoteを読み取り専用リテラルに設定します。代わりにchar quote[] =を使用してください。

char quote[] = "To be or not to be, that is the question."; 
char *quotePtr; 
for (quotePtr = quote; *quotePtr != '\0'; quotePtr++){ 
    *quotePtr = tolower(*quotePtr); 
} 

Test

char quote[] = "To be or not to be, that is the question."; 
int i; 
for (i = 0; quote[i] != '\0'; i++){ 
    quote[i] = tolower(quote[i]); 
} 

Test:インデックスを使用

+1

これは、読み取り専用ページに文字列リテラルがあるため、アクセス違反が発生する可能性が最も高いことがわかりますか? – ChrisWue

+0

@ChrisWueああ、ありがとう、修正されました。 – Dukeling

+0

@Dukeling: - char * quote = "するかしないかを質問する";別のchar * quotePtr = quoteを取る。同じことができます.. char * quote = "be be or not ... question"を取って何が問題なのですか? – kTiwari

0

forイニシャライザにquoteを再割り当てしています。これは無効で、*quote != NULL部分で参照解除するためアクセス違反が発生します。

意味的にNULL'\0'は同等ですが、構文的に私はこれを好むでしょう。この方法を使うと、文字列の先頭にポインタを置くことに注意してください。

wchar const_t* quote = L"To be or not to be, that is the question."; 

for(wchar_t* c = quote; *c != '\0'; c++) { 

    *c = tolower(*c); 
} 

は、代わりにインデックスを使用して:

wchar const_t quote[] = L"To be or not to be, that is the question."; 

for(size_t i = 0; i < sizeof(quote); i++) { 

    quote[i] = tolower(quote[i]); 
} 

+0

ポインタを間接的に逆参照して再割り当てするのはなぜですか?あなたのコードは同じなので、理由は間違っていると思われます。 – Dukeling

+0

'wchar const_t * quote'は定数文字列リテラルで、修正できないのでコードが失敗します。 – ChrisWue

2

がに拡張としてこれを考慮してください(quoteの値がコンパイル時に知られていない場合sizeofのセマンティクスが変更されることに注意してください)答えはDukeling

を使用した場合
char *quote = "Hello World"; 

これは読み取り専用の文字列を作成します。これは、より簡単な方法で内容を変更できないことを意味します。

Here *quote points to 'H' 
BUT, you cannot do *quote = 'A'; 
This will give you an error. 

文字列内の文字を変更したい場合は、配列を使用することをお勧めします。

char quote[] = "Hello World"; 
Here also *quote points to 'H' 
BUT, in this case *quote = 'A' is perfectly valid. 
The array quote will get changed. 
関連する問題