Thread: Possible pointer issues...

  1. #1
    Registered User
    Join Date
    Feb 2019
    Posts
    9

    Possible pointer issues...

    Hello... I'm trying to learn C after using a higher level language for several years. Honestly I feel like I am learning to walk again... Having a tough time!

    In the code below I am attempting to extract the longest word from a string. I am still learning pointers so I very well may have messed that up.
    It "seems" as though my new[] char array is holding the largest word when the program finishes, yet it doesn't print in the final print statement that's outside the for loop.

    Here is the code:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    void append(char *s, char c) {
            int len = strlen(s);
            s[len] = c;
            s[len+1] = '\0';
    }
    
    int main() {
        int i, c = 0, l = 0;
        char line[] = "Here is a phrase to test";
        char new[] = "\0";
        int length = strlen(line);
        for (i = 0; i <= length; i++, c++) {
            if (line[i] != ' ' && line[i] != '\0')
                append(new, line[i]);
            else {
                if (c > l) {
                    l = c;
                    new[i] = '\0';
                    printf("longest so far: %s length: %d\n", new, strlen(new));
                }
                memset(&new[0], 0, sizeof(new));
                c = 0;
            }
            printf("%s\n", new);
        }
        printf("Final output:  %s", new);
        return (0);
    }
    Here is the output from all of the print statements:

    Code:
    H
    He
    Her
    Here
    longest so far: Here length: 4
    
    i
    is
    
    a
    
    p
    ph
    phr
    phra
    phras
    phrase
    longest so far: phrase length: 6
    
    t
    to
    
    t
    te
    tes
    test
    
    Final output:  
    RUN FINISHED; exit value 0; real time: 0ms; user: 0ms; system: 0ms

    Any tips would be appreciated. Thank you...

    Here's the code without the print statements...
    Last edited by StruggleBot; 02-16-2019 at 08:07 PM.

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Code:
    char new[] = "\0";
    Change to
    Code:
    char new[100] = "\0";
    new[] would only be one char long.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You should be aware that because you didn't specify the array size, your new array's size is that of its initialiser, i.e., it can only ever store an array of a maximum size of 2, i.e., it can only store a string of a maximum length of 1. You should specify a suitable size to avoid this.

    Also, your append function is rather inefficient when used the way you use it because you keep finding the string length (a linear time operation) and then appending. Ideally, you would either keep track of the string length so you can append in constant time, or keep track of the end of the string (say with a pointer) so you can append in constant time.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User
    Join Date
    Dec 2017
    Posts
    1,628
    What high-level language did you use?

    It's odd to make your own strcat by using strlen. (That seems like cheating!)

    new needs enough space to hold the string. If you don't say how big it is, it is only made big enough to contain the original string. Since you have set it to "\0" it will be 2 chars long (the double quotes always add a \0 at the end).
    Code:
    char new[1000] = "";
    strlen returns a size_t, so if you want to print it with %d you need to cast it to an int.

    Why would you expect new to contain anything in the end? You keep erasing it with memset.

    What do you expect the program to do?
    A little inaccuracy saves tons of explanation. - H.H. Munro

  5. #5
    Registered User
    Join Date
    Feb 2019
    Posts
    9
    Hmmm I tried changing the array size mentioned in each of all above posts. I still can't seem to print that final output though? Thank you for replying...

  6. #6
    Registered User
    Join Date
    Feb 2019
    Posts
    9
    Ok I made a few edits for readability... I still seem to be having the same issue though... Any pointers? sorry... haha... oh and I am interning as a Python developer.... To be honest... I can see why people made interpreters such as python.exe and perl. I see a lot of similarities in C as it was used to make those interpreters. I must admit though... I really like the "mechanical" feeling I get when programming C. I just don't completely get it yet

    here's the new code and output:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    void append(char *s, char c) {
            int len = strlen(s);
            s[len] = c;
            s[len+1] = '\0';
    }
    
    int main() {
        int i, c = 0, l = 0;
        char line[] = "Here is a phrase to test";
        char new[100] = "\0";
        int length = strlen(line);
        for (i = 0; i <= length; i++) {
            if (line[i] == '\0' || line[i] == ' ') {
                printf("c: %i\n", c);
                if (c > l) {
                    l = c;
                    printf("longest so far: %s\n", new);
                }
                c = 0;
                memset(&new[0], 0, sizeof(new));
            }
            else {
                append(new, line[i]);
                c++;
            }
            printf("%s\n", new);
        }
        printf("Final output: %s", new);
        return (0);
    }
    and output:

    Code:
    H
    He
    Her
    Here
    c: 4
    longest so far: Here
    
    i
    is
    c: 2
    
    a
    c: 1
    
    p
    ph
    phr
    phra
    phras
    phrase
    c: 6
    longest so far: phrase
    
    t
    to
    c: 2
    
    t
    te
    tes
    test
    c: 4
    
    Final output: 
    RUN FINISHED; exit value 0; real time: 0ms; user: 0ms; system: 0ms
    Last edited by StruggleBot; 02-16-2019 at 08:45 PM.

  7. #7
    Registered User
    Join Date
    Dec 2017
    Posts
    1,628
    I already explained why your "final output" doesn't print anything.
    Here's a rewrite of your program that at least makes sense:
    Code:
    #include <stdio.h>
    #include <string.h>
     
    void append(char *s, char ch, int pos) {
        s[pos] = ch;
        s[pos + 1] = '\0';
    }
     
    int main() {
        char word[100] = "", longest_word[100] = "";
        char line[] = "Here is a phrase to test";
        int length = strlen(line);
        int longest = 0;
     
        for (int i = 0, len = 0; i <= length; i++) {
            if (line[i] != ' ' && line[i] != '\0')
                append(word, line[i], len++);
            else {
                printf("\"%s\" len: %d\n", word, len);
                if (len > longest) {
                    longest = len;
                    strcpy(longest_word, word);
                }
                word[0] = '\0';
                len = 0;
            }
        }
     
        printf("longest word is \"%s\", length: %d\n", longest_word, longest);
     
        return 0;
    }
    A little inaccuracy saves tons of explanation. - H.H. Munro

  8. #8
    Registered User
    Join Date
    Feb 2019
    Posts
    9
    I had originally tried strcpy with no luck... possibly because I wasn't initializing char arrays like you did in your version... cool.. Thanks for pointing out the memset issue too... I think I had been staring at it for too long scratching my head.

    So does strcpy() only work in your version because you set the initial char arrays to the same size? word and longest_word?
    Last edited by StruggleBot; 02-16-2019 at 09:28 PM.

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Seeing that you're regarding "words" as contiguous non-space characters separated by spaces, it seems to me that an approach with strtok would be simpler:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(void)
    {
        char input_line[] = "Here is a phrase to test";
    
        char *longest_token = NULL;
        size_t longest_token_len = 0;
    
        const char *token_delimiter = " ";
        char *token = strtok(input_line, token_delimiter);
        while (token)
        {
            size_t token_len = strlen(token);
            if (token_len > longest_token_len)
            {
                longest_token_len = token_len;
                longest_token = token;
            }
    
            token = strtok(NULL, token_delimiter);
        }
    
        if (longest_token)
        {
            printf("Longest word: %s\n", longest_token);
        }
    
        return 0;
    }
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    Registered User
    Join Date
    Dec 2017
    Posts
    1,628
    Quote Originally Posted by StruggleBot View Post
    So does strcpy() only work in your version because you set the initial char arrays to the same size? word and longest_word?
    They don't need to be the same size. The destination (first) parameter just needs enough space to hold what you are copying from the source.

    laserlight has shown the use of strtok, which is a good idea in this case since it writes null chars ('\0') into the input line after each word so that instead of strcpy'ing the longest word into it's own string, you can just save a pointer pointing to the longest word in the input line.
    A little inaccuracy saves tons of explanation. - H.H. Munro

  11. #11
    Registered User
    Join Date
    Feb 2019
    Posts
    9
    Okay thank you all very much for the help!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointer conversion issues
    By bremenpl in forum C Programming
    Replies: 6
    Last Post: 12-21-2015, 02:11 PM
  2. pointer issues
    By Bobbel in forum C Programming
    Replies: 23
    Last Post: 08-14-2010, 05:11 PM
  3. Pointer/Struct issues
    By GoatMafioso in forum C Programming
    Replies: 6
    Last Post: 04-16-2010, 06:51 PM
  4. Issues with pointer and freeing its associated memory
    By tytelizgal in forum C Programming
    Replies: 10
    Last Post: 10-17-2008, 03:00 PM
  5. Pointer issues (I think)
    By rissarissole in forum C Programming
    Replies: 5
    Last Post: 08-16-2008, 08:48 AM

Tags for this Thread