Thread: Pointer to pointer and pointer to array disambiguation

  1. #1
    Registered User
    Join Date
    May 2016
    Posts
    104

    Pointer to pointer and pointer to array disambiguation

    I was under the impression that these two were the same, yet, after having problems doing this:
    Code:
        char **ptr;
        char dd_arr[2][4]; // initialize with something here...
      
        ptr = dd_arr; //compiler error: incompatible pointer types assigning to char **' from 'char [2][4]' [-Wincompatible-pointer-types]
    I went on a google search that led me to believe they might be different after all.

    I'm confused now. *ptr, holds the address of a pointer that holds the address of a char. Similarly, dd_arr[0] holds the address of an area in memory, where the address of a char is stored. I'm not understanding the difference. Why can I do *ptr = *dd_arr, but not ptr = dd_arr?


    Thanks.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,163
    The 'arrays decay to pointers' rule only applies to the outermost dimension of the array.

    So.
    Code:
    char dd_arr[2][4]; // initialize with something here...
    char (*ptr)[4];  // ptr to an array of char[4]
    ptr = dd_arr;  // or ptr = &dd_arr[0] etc
    You need the () in the pointer declaration, because char *ptr[4] is an array of pointers to char.
    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. Passing 2D array to function via pointer of pointer
    By sean_cantab in forum C Programming
    Replies: 4
    Last Post: 05-09-2016, 10:15 AM
  2. Replies: 16
    Last Post: 01-28-2010, 02:44 AM
  3. Replies: 3
    Last Post: 10-30-2009, 04:41 PM
  4. Replies: 1
    Last Post: 03-24-2008, 10:16 AM
  5. Replies: 4
    Last Post: 08-27-2007, 11:51 PM

Tags for this Thread