I'm trying to increment a char** and I am unable to understand the dynamic of it

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • moutabreath
    New Member
    • Nov 2012
    • 1

    #1

    I'm trying to increment a char** and I am unable to understand the dynamic of it

    I have the following char** that I'm trying to get data about:
    Code:
    int print_word_count(char **argv) {
      int count = 0;
      char **a = argv;
      while(a++){
       printf("%s\n",*a);
        ++count;
      }
      printf("The sentence contains %d %s.\n", count, words(count));
      return count
    using gdb I get a seg fault on the while loop. trying to incure about '*a' after incrementing shows it has address 0x00
    couldn't find explanation to it on google
    Last edited by Rabbit; Nov 13 '12, 04:49 PM. Reason: Please use code tags when posting code.
  • vikramjit
    New Member
    • Nov 2012
    • 2

    #2
    a and *a even after legal limit may not contain null hence after the actual content is read *a points to firbidden location as a result on 'printf' you get an error.

    You should know prior to calling 'print_word_cou nt' how many words you have

    just for your information..lo ok at the declaration of main that accepts command line args and try to figure out why first argument is the count of arguments.
    Good luck.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      Your code assumes that argv points to an array of char pointers and that the last entry in this array is NULL. Apparently the caller did not set up the array that way so your code steps past the end of the array -- triggering a seg fault.

      Typically, functions are passed both a pointer to the start of an array and the number of entries in the array. Is the argv argument to print_word_coun t related to the argv argument to main? If so, you should note that argc is another argument to main.

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        Line 4 tests the value of a. If it is nonzero, then a is incremented (to point to the next entry in the array) and the loop body is executed. This means that you only test the value of a after you dereference it.

        Comment

        Working...