Thread: Pointer as an array name - help

  1. #1
    Registered User
    Join Date
    Jul 2011
    Posts
    46

    Pointer as an array name - help

    I'm having a hard time grasping this code

    Code:
    #define N 10
    int a[N], i, sum = 0, *p = a;
    for (i = 0; i < N; i++)
    sum += p[i];
    if i Do
    Code:
     a[10] = {1,2,3,4,5,6,7,8,9,10}
    int *p = a;
    wouldn't I reference each element as *p[i] or to get address as &p[i]? Why is the dereference skipped? I would understand that p[i] in the example would be the address and not the actual value. Help me understand this.

  2. #2
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    You set a pointer to array a.I can not understand your question

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    No, a[i] would give you an int. You're getting the ith element of an array of ints, which is an int.

    a is an array of 10 integers. This type is automatically convertible to a pointer to int.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    The best way to understand it, is to add a print statement inside the loop.
    Code:
    for(i=0;i<N;i++) {
       printf("a[%d] is:   p+i is: %p  *(p+i) is: %d\n",a[i],p+i, *(p+i));
       //maybe print up some sums?
    }
    Include EVERYTHING you're not sure of, in the print statement - even if it's wrong and won't even compile. Find out WHY any bad part of it, won't compile, and find out EXACTLY what every little expression of the array, will give you.

    Learning by doing (exploring yourself), is a great way to learn something. Some educators even use the maxim "Learning by doing is not A way to learn, it is the ONLY way to effectively learn."

    That's one of the great things about programming - you can explore on your own, so much, very easily.

    P.S. Be certain to nail down the zero based indexing that C arrays use, also!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 01-28-2010, 02:44 AM
  2. Casting from a 1D array pointer to a scalar pointer
    By komkamol in forum C Programming
    Replies: 8
    Last Post: 09-25-2009, 01:44 AM
  3. pointer to pointer that points to a char array
    By steve1_rm in forum C Programming
    Replies: 2
    Last Post: 01-14-2009, 12:03 AM
  4. Replies: 1
    Last Post: 03-24-2008, 10:16 AM
  5. A pointer to a character pointer array... can't pass
    By Lynux-Penguin in forum C Programming
    Replies: 9
    Last Post: 10-12-2003, 10:53 PM