Thread: Returned from strstr() and pointers...

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    84

    Returned from strstr() and pointers...

    I am searching for a specific word in a sentence and check for it using strstr(). Then check the return of it to see if it returns NULL to continue onward. Finally, check to see if first char is a "space" and if so, change it to "9". MY question is, from what is returned (the base address of the substring of that sentence and what was after it), how can I copy that to another string to use it.

    So far...
    Code:
         char *ptr, *ptr_str;
         char *segment[5];
    
    /* Omit code for ease. */
    
         ptr = strstr(string, segment[i]);
    
         if(ptr != NULL){
    
            printf("---> Residual part of the string was %s\n", ptr);
    
            ptr_str = malloc(sizeof(ptr) + 1);
            strcpy(ptr_str, ptr);
            printf("Returned from first successful strstr call is: %s.\n",
                      ptr_str);
    
    /*     See if their is an space present in the present wx group and 
            truncate/remove it if necessary. */
    
            if(ptr_str[0] == " ") ptr_str[0] = "9"; /* Assign the first character to a random in -- "9"; */

    I get compile error:
    array_search_strstr.c:warning: comparison between pointer and integer
    array_search_strstr.c:warning: assignment makes integer from pointer without a cast

    Confusing as it prints out the residual part in the print statement...

    Any idea?

  2. #2
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    ptr_str = malloc(sizeof(ptr) + 1); // WRONG!
    You need to use strlen() function. not sizeof operator. sizeof(ptr) ,in this case, will give you the size of pointer.ie sizeof(char*) sizeof a char pointer. usually 2 or 4 bytes.


    Code:
            if(ptr_str[0] == " ") ptr_str[0] = "9"; /* Assign the first character to a random in -- "9"; */
    To compare C strings, you need to use strcmp() function.
    In your case, you can just check whether the first char is
    Edit: space (' ') char/ if( ptr_str[0] == ' ' )
    ptr_str[0] type is char. and "9" is a string literal.
    Change it to ptr_str[0] = '9'; // '9' is char literal.
    Last edited by Bayint Naung; 11-29-2010 at 12:36 AM. Reason: Edit:

  3. #3
    Registered User
    Join Date
    Feb 2010
    Posts
    84
    (explicative) Im embarrass to say that I didn't catch those two...

  4. #4
    Registered User
    Join Date
    Nov 2010
    Location
    xian china
    Posts
    31
    "" is a string literal, include '\0' at the end.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. !@#&*!!# strstr()
    By Sebastiani in forum C Programming
    Replies: 10
    Last Post: 09-05-2001, 01:19 AM