In this lesson, we discuss C pointer and arrays. Pointers are one of the most important concepts in C language, their use in various cases makes programming easier, and sometimes the only solution is to use pointers.
Pointers and arrays are closely related, and any operation that is done through array indexing; can also be done with pointers. The advantage of using a pointer over using an index is to increase the speed of operation, although it is easier for beginners to use an index.
By defining an array, several bytes of memory are assigned to it, and the starting address of these bytes is assigned to the name of the array, which is also called the base address of the array. This name is a constant pointer because it is assigned a fixed address from memory, which cannot be changed. Pay attention to the following example:
int key[10];
int *pt, *pr;
Now we want to assign the address of the array to the pointers. Both of the following statements are true:
pt = key;
pr = key + 2;
Note that writing a statement such as key = pt; is wrong because the key is a constant pointer, and its value cannot be changed.
When a pointer contains the address of an array, that pointer is addressable, like the array’s name. For example, expressions like key[3], pt[3], and pr[3] mean the fourth element of the array. To access the content of the array, you can use statements like *(key + 3), *(pt + 3), and *(pr+1) used.
Note that because the pt and pr pointers point to different array elements, different values have been added to them to access the content of the fourth array’s element.
Now let’s pay attention to the details of this example. Suppose that the key points to cell number 3200 in memory; Because each cell of this array is of int type, it occupies two bytes. Therefore, the address of the second element is 3202, which can be accessed as key+1 or key[1]. In the key+1 expression, we added one to the key, but in the address conversion, two are added to the real address of the key. This is because the compiler knows that the key is a pointer of type int and must add two units to it in each increment.
Look at the following example:
float *x, *y, *z, total[]={5,10,15,20,25};
int num[10] = {2,4,6,8,10,12,14,16,18,20};
int p, q;
p = num;
q = num + 4;
x = total + 1;
y = &total[0];
++x;
z = x - 1;
z--;
As mentioned before, pointers contain addresses, and the name of any string is a constant address(pointer). The string’s name specifies its first element address. Consider the following example:
char table[5];
char *p;
p = &table;