Thread: Confused with following code

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    17

    Confused with following code

    Code:
    char *str = "The quick brown fox jumped over the lazy dogs.";
    char *p;
    
    p = strstr(str, "lazy");
    printf("%s\n", p); // "lazy dogs."
    
    // p is NULL after this, since the string "wombat" isn't in str:
    p = strstr(str, "wombat");
    I'm trying to implement my own strstr() function but my knowledge of pointers is quite fuzzy.

    First of all I'm confused with the first line lol.
    Within C programming I've been using arrays to manipulate strings. With this initialization, I'm assuming it sets a pointer to that string.

    Here's where I have trouble with pointers. When I first tried to use how strstr() I saw
    Code:
    #include <string.h>
    char *strstr( const char *str1, const char *str2 );
    on elook.org I thought that the parameters should be pointers but that didn't make sense and did something like char *strstr("asdfg","asdf"); First of all I failed to realize that I should have assigned it to a pointer variable and second there shouldn't be a * on the strstr function. I seem to have trouble with pointers.

    I don't really understand the address and pointers. When I first thought of strstr I was thinking that it was going to literally return the address of str2 in str1 and got confused with that. With the printf of "lazy dogs" I'm guessing that it prints whatever the pointer is pointing at until the end of the text.

    I guess I should really read up on pointers and addresses.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    A "string" has a type which is usually const char * (on new compilers) or char * on really old compilers.

    So things like
    Code:
    strstr(str, "lazy");
    strstr("The quick brown fox jumped over the lazy dogs.", "lazy");
    can be regarded as largely equivalent.

    Take a look over here
    A Tutorial on Pointers and Arrays in C
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Proposal: Code colouring
    By Perspective in forum A Brief History of Cprogramming.com
    Replies: 28
    Last Post: 05-14-2007, 07:23 AM
  2. Values changing without reason?
    By subtled in forum C Programming
    Replies: 2
    Last Post: 04-19-2007, 10:20 AM
  3. True ASM vs. Fake ASM ????
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 7
    Last Post: 04-02-2003, 04:28 AM
  4. Replies: 4
    Last Post: 01-16-2002, 12:04 AM
  5. I am confused with this code that somebody gave me
    By face_master in forum C++ Programming
    Replies: 14
    Last Post: 11-16-2001, 01:43 AM