#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    30
    Rep Power
    2

    Questions about C arrays


    I got some questions about C arrays.
    First, why is an array a pointer to its first element?
    Second, what is the difference between char and int arrays? How are they different from allocating space in memory?
    Is it like 4 bytes of memory for each element of the int array , and 1 byte for each element of the char array?
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Location
    India
    Posts
    95
    Rep Power
    4
    >>why is an array a pointer to its first element?
    its because by using first element address it can access all other member by index.

    a[1] and *(a+1) are same so from first element address it can get all other element address using index.

    >>Second, what is the difference between char and int arrays? How are they different from allocating space in memory?

    in char array each element is of 1 byte and in int array each element of 4 bytes(depending on size of int).

    >>Is it like 4 bytes of memory for each element of the int array , and 1 byte for each element of the char array?

    yes.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    109
    Rep Power
    3
    Originally Posted by MiguelC
    I got some questions about C arrays.
    First, why is an array a pointer to its first element?
    Second, what is the difference between char and int arrays? How are they different from allocating space in memory?
    Is it like 4 bytes of memory for each element of the int array , and 1 byte for each element of the char array?

    An array never becomes a pointer and a pointer is not the same type as an array. What is true is that array names act like pointer values in nearly every context. But not always. An array name as the operand of the sizeof operator evaluates to the size of the entire array, not the size of a pointer, just one example of an array name not behaving like a pointer.

    Btw, an array of ints is suitable for chars, because char is a small int.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    30
    Rep Power
    2
    Code:
    char array[] = "String";
    In here if the arrays's name is not a pointer variable, how did it contain the first element's address?

IMN logo majestic logo threadwatch logo seochat tools logo