How to literate a const char*

S

silverburgh.meryl

Hi,

how can I literator a const char*?

I have this code, but it results in an infinite loop. It never exits
the while (p1 != '\0') loop

void teststr( const char *str1) {
char* p1 = (char*)str1;


while (p1 != '\0') {
//....
p1 ++;
}

}

and i call teststr like this:

teststr("http://www.cnn.com");

Can you please tell me why i never exit the while loop?

Thank you.
 
B

Ben Pfaff

I have this code, but it results in an infinite loop. It never exits
the while (p1 != '\0') loop

void teststr( const char *str1) {
char* p1 = (char*)str1;

This is questionable. If you don't need to modify str1, then
declare p1 as const and drop the cast. If you do need to modify
str1, then don't declare str1 as const and drop the cast.
while (p1 != '\0') {

Should be
while (*p1 != '\0')
Note the *.
 
C

Christopher Benson-Manica

This is questionable. If you don't need to modify str1, then
declare p1 as const and drop the cast. If you do need to modify
str1, then don't declare str1 as const and drop the cast.

Note that OP passed a string literal to this function, so it seems
that the former is the right advice.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top