CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Jan 2012
    Location
    USA
    Posts
    91

    [RESOLVED] A pointer to an array: int* p = arr; vs. int (*p2)[10] = &arr; ?

    Hello,

    Code:
    int arr[10];
    int* p = arr;
    int (*p2)[10] = &arr;
    So, pointer p is a pointer to an array, I can use it to access elements of arr as in *(p+5).

    Pointer p2 is a pointer to an array of ten integers. What is it for, how can I use it to access elements of arr?

    Thank you.

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: A pointer to an array: int* p = arr; vs. int (*p2)[10] = &arr; ?

    In this case, there probably is not much use for p2. However, if you were dealing with a 2D array, then it could become useful.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: A pointer to an array: int* p = arr; vs. int (*p2)[10] = &arr; ?

    Quote Originally Posted by vincegata View Post
    So, pointer p is a pointer to an array, I can use it to access elements of arr as in *(p+5).
    Strictly, p is a pointer to the first element of an array.
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

  4. #4
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    4,626

    Re: A pointer to an array: int* p = arr; vs. int (*p2)[10] = &arr; ?

    Strictly, p is a pointer to the first element of an array.
    true, but in the way the 2nd pointer is defined in the OP, it's a pointer to an array of (an array of) 10 ints (and not a pointer to (an array of) ints). and p2[0] points to the first of said arrays of 10 ints.
    p2[1] would point to another array of 10 ints.

    you can access the first int - element as p2[0][0] (=return the 1st int of the 1st array of 10 ints).
    or alternatively you could (for the first element) also write this as: (*p2)[0] (the parens are significant here. or you'll get *(p2[0]))

  5. #5
    Join Date
    Jan 2012
    Location
    USA
    Posts
    91

    Re: A pointer to an array: int* p = arr; vs. int (*p2)[10] = &arr; ?

    I see, thanks guys for all responses.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured