Thread: Accessing elements in an array of pointers to arrays

  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    35

    Accessing elements in an array of pointers to arrays

    I have an array of pointers that point to arrays of characters and what I'd like to do is access the 4th letter in the 3rd word and change it. I've tried tons of combinations but I can't seem to get a pointer to what I want, any suggestions. Thanks. PS I know the code doesn't print anything out yet.

    Code:
    int main()
    {
       char *words[] = {"One", "Two", "Three", "Four"};
       (*words[2]) + 3 = 'D'; //I'd like to turn the 1st 'e' in Three into a D
       return 0;
    }

  2. #2
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    It would be
    Code:
    *(words[2]+3) = 'D';
    or simpler and better
    Code:
    words[2][3] = 'D';
    think that words is a char**, words[] is a char* and words[][] is a char

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    35
    Those are both incorrect (for me anyways) and all give segmentation fault errors. I even tried changing char *words[] to char **words[] and I just get different errors using that.

  4. #4
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Initialized char *s are constant and cannot be modified. The string is loaded into read-only memory.

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You have an array of pointers to characters, not a 2D array of characters. You assign those pointers string literals, which you shouldn't attempt to modify. You can make the pointer point elsewhere, but you cannot change what your string literals contain.


    Quzah.
    Hope is the first step on the road to disappointment.

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Maybe what you want is more like:

    Code:
    int main()
    {
      int i;
      char words[4][6] = {{"One"}, {"Two"}, {"Three"}, {"Four"}};
      (words[2][3] = 'D'; //I'd like to turn the 1st 'e' in Three into a D
    
      for(i=0;i<4;i++)
        printf("\n %s", words[i]);
    
       return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. warning: excess elements in array initializer
    By redruby147 in forum C Programming
    Replies: 6
    Last Post: 09-30-2009, 06:08 AM
  2. Replies: 4
    Last Post: 11-02-2006, 11:41 AM
  3. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  4. Passing pointers between functions
    By heygirls_uk in forum C Programming
    Replies: 5
    Last Post: 01-09-2004, 06:58 PM
  5. Array of pointers
    By falconetti in forum C Programming
    Replies: 5
    Last Post: 01-11-2002, 07:26 PM