DEV Community

chaitanya0247
chaitanya0247

Posted on

array and pointers

Arrays and pointers are closely related in C. An
array declared as
int A[10];
can be accessed using its pointer representation. The name
of array A is a constant pointer to the first element
of the array. So A can be considered a const int*. Since A
is a constant pointer, A = NULL would be an illegal
statement.
Other elements in the array can be accessed using their
pointer representation as follows.
&A[0] = A
&A[1] = A + 1
&A[2] = A + 2
…..
&A[n-1] = A + n-1
If the address of the first element in the array of A (or
&A[0]) is FFBBAA0B then the address of the next element
A[1] is given by adding 4 bytes to A.
That is
&A[1] = A + 1 = FFBBAA0B + 4 = FFBBAA0F
And
&A[2] = A + 2 = FFBBAA0B + 8 = FFBBAA13
Note that when doing address arithmetic, the number of
bytes added depends on the type of the pointer. That is
int* adds 4 bytes, char* adds 1 byte, etc. You can type in
this simple program to understand how a 1-D array is
stored.
Array of Pointers
C arrays can be of any type. We define an array of ints,
chars, doubles, etc. We can also define an array of pointers
as follows. Here is the code to define an array of n char
pointers or an array of strings.
char* A[n];
each cell in the array A[i] is a char* and so it can point
to a character. You should initialize all the pointers (or
char*) to NULL with
for (i=0; I <n; i++)
A[i] = NULL;
Now if you would like to assign a string to each A[i] you
can do something like this.
A[i] = malloc(length_of_string + 1);
Functions that take pointer arguments
Pointers or memory addresses can be passed to a function as
arguments. This may allow indirect manipulation of a memory
location. For example, if we want to write a swap function
that will swap two values, then we can do the following.
void intswap(int* ptrA, int* ptrB){
int temp = *ptrA;
*ptrA = *ptrB;
*ptrB = temp;
}
To use this function in the main, we can write the code as
follows.
int A = 10, B = 56;
int swap(&A, &B);
note that the addresses of the variables A and B are passed
into the int swap function and the function manipulates the
data at those addresses directly. This is equivalent to
passing values by “reference”. It is passing the
values that are addresses instead of copies of variables.
However, this can be dangerous since we are giving access to
the original values.
One way to avoid this situation is to provide only “read”
access to the data using a pointer

Top comments (0)