How to literate a const char*

Discussion in 'C Programming' started by silverburgh.meryl@gmail.com, Jul 14, 2007.

  1. Guest

    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.
     
    , Jul 14, 2007
    #1
    1. Advertising

  2. Ben Pfaff Guest

    "" <> writes:

    > 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 *.

    > //....
    > p1 ++;
    > }
    >
    > }


    --
    "Am I missing something?"
    --Dan Pop
     
    Ben Pfaff, Jul 14, 2007
    #2
    1. Advertising

  3. Ben Pfaff <> wrote:

    > "" <> writes:


    > > 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.


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

    --
    C. Benson Manica | I *should* know what I'm talking about - if I
    cbmanica(at)gmail.com | don't, I need to know. Flames welcome.
     
    Christopher Benson-Manica, Jul 15, 2007
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Thomas Matthews
    Replies:
    5
    Views:
    2,457
    tom_usenet
    Aug 2, 2004
  2. Santa
    Replies:
    1
    Views:
    1,095
    Mark A. Odell
    Jul 17, 2003
  3. Replies:
    24
    Views:
    841
    Netocrat
    Oct 30, 2005
  4. lovecreatesbeauty
    Replies:
    1
    Views:
    1,071
    Ian Collins
    May 9, 2006
  5. Javier
    Replies:
    2
    Views:
    574
    James Kanze
    Sep 4, 2007
Loading...

Share This Page