Lucy Luo
Lucy Luo

Reputation: 71

How to loop through a string created by pointer

What I want to do is to iterate through the quote till the end of the quote/(*quote has nothing in it). Is my code valid?

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

Upvotes: 7

Views: 69022

Answers (3)

nikoo28
nikoo28

Reputation: 2971

Consider this as an expansion to the answer given by Dukeling

When you use

char *quote = "Hello World";

This makes a read-only string, means that you can't change its contents in a simpler way.

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

If you wish to make changes to the characters in a string, it is a good habit to use arrays.

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.

Upvotes: 4

Bernhard Barker
Bernhard Barker

Reputation: 55589

You probably need another pointer to traverse the array, otherwise access to your original string will be lost.

And preferably only use NULL for pointers.

Don't use 0 as the initial value, unless you want to use indices instead (see below).

Doing char *quote = will simply make quote point to the read-only literal, instead of copying the string. Use char quote[] = instead.

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

Test.

Using indices:

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.

Upvotes: 13

Dai
Dai

Reputation: 155055

You're reassigning quote in your for initializer, which is invalid and will cause an access-violation because you're dereferencing it in the *quote != NULL part.

Semantically NULL and '\0' are equivalent, but syntactically I'd prefer this. Note that by using this approach you keep a pointer to (the start of) the string.

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 );
}

alternatively using an index:

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] );
}

(note that the semantics of sizeof will change if the value of quote is not known at compile time)

Upvotes: 0

Related Questions