When memory is allocated to an array, its base address is fixed and it cannot be changed during program execution. In other words, an array name is an address constant. Therefore, its value cannot be changed.
DIFFERENCE
BETWEEN ARRAY NAME AND POINTER
When
memory is allocated to an array, its base address is fixed and it cannot be
changed during program execution. In other words, an array name is an address
constant. Therefore, its value cannot be changed. To ensure that the address of
the array does not get changed even inadvertently, C does not allow array names
to be used as an Ivalue. Hence, array names cannot appear on the left side of
the assignment operator.
However,
you may declare a pointer variable of appropriate type that points to the first
element of the array and use it as Ivalue. Figure 7.5 shows two sets of codes.
The first code gives an error as the array name is being used as an Ivalue for
the ++ operator. The second code shows the correct way of doing the same thing.
Second
thing to remember is that an array cannot be assigned to another array. This is
because an array name cannot be used as the lvalue.
int arr1 []={1,2,3,4,5); *
int arr2 [5];
arr2 = arr1; // ERROR
But
one pointer variable can be assigned to another pointer variable of the same
type. Therefore, the following statements are valid in C.
int arr1 []={1,2,3,4,5);
int *ptrl, *ptr2;
ptr1 = arr1;
ptr2 = ptr1;
When
we write ptr2 = ptr1, we are not copying the data pointed to. Rather, we are
just making two pointers point to the same location. This is shown in Figure
7.6.
Third
point of difference lies with the return value of the address operator. The
address operator returns the address of the operand. But when an address
operator is applied to an array name, it gives the same value as the array
reference without the operator. Therefore, arr
and &arr give the same value.
However, this is not true for a pointer variable.
Last
but not the least, the sizeof
operator when applied to an array name returns the number of bytes allocated
for the array. But in case of a pointer variable, the sizeof operator returns
the number of bytes used for the pointer variable (machine dependent). Look at
the following code which illustrates this concept.
main()
{
int arr[]={1,2,3,4,5);
int *ptr;
ptr = arr;
printf("\n Size of array =
%d", sizeof (arr));
printf("\n Size of pointer
variable = %d", sizeof (ptr));
}
Output
(On Turbo C)
Size of array = 10
70 Size of pointer variable = 2
Programming in C: Unit III (b): Pointers : Tag: : with Example C Programs - Difference Between Array Name and Pointer
Programming in C
CS3251 2nd Semester CSE Dept 2021 | Regulation | 2nd Semester CSE Dept 2021 Regulation