| Pointers |
| |
| Pointer & Array |
| |
| Pointers and arrays are very closely linked in C. |
| |
| Hint: Think of array elements arranged in consecutive memory locations. |
| |
| Consider the following: |
| |
| int a[10], x; |
| int *pa; |
| pa = &a[0]; /* pa pointer to address of a[0] */ |
| x = *pa; |
| |
| /* x = contents of pa (a[0] in this case) */ |
| |
 |
| |
| Warning: There is no bound checking of arrays and pointers so you can easily go beyond array memory and overwrite other things. |
| |
| C however is much more subtle in its link between arrays and pointers. |
| |
| For example we can just type: |
| |
| pa = a; |
| instead of |
| pa = &a[0] |
| and |
| a[i] can be written as *(a + i). |
| i.e. &a[i] =a + i. |
| |
| We also express pointer addressing like this: |
| |
| pa[i] =*(pa + i). |
| |
| However pointers and arrays are different: |
| |
| A pointer is a variable. We can do pa = a and pa++. |
| |
| An Array is not a variable. a = pa and a++ ARE ILLEGAL |
| |
| This stuff is very important. Make sure you understand it. We will see a lot more of this. We can now understand how arrays are passed to functions. |
| |
| When an array is passed to a function what is actually passed is its initial element location in memory |
| |
| So: strlen(s) strlen(&s[0]) |
| |
| This is why we declare the function: |
| |
| int strlen(char s[]); |
| |
| An equivalent declaration is: |
| |
| int strlen(char *s); |
| |
| since char s[] is equivalent to char *s. |
| |
| strlen () is a standard library function that returns the length of a string. |
| |
| Let's look at how we may write a function: |
| |
| int strlength(char *s) |
| { |
| char *p = s; |
| while (*p != '\0'); |
| p++; |
| return p-s; |
| } |
| |
| Now let’s write a function to copy a string to another string. strcpy () is a standard library function that does this: |
| |
| void strcopy (char *s, char *t) |
| { while ( (*s++ = *t++) != `\0' );} |
| |
| This uses pointers and assignment by value. |
| |
| Note: Uses of Null statements with while. |
| |
| Malloc Library Function |
| |
| Function: Allocates main memory |
| Syntax: void*malloc(size_t size); |
| Prototype in: stdlib.h, alloc.h |
| |
| Remarks: malloc allocates a block of size bytes from the C heap memory. It allows a program to allocate memory explicitly, as it is needed and in the exact amounts needed. |
| |
| Calloc Library Function |
| |
| Function: Allocates main memory |
| Syntax: void*calloc(size_t n size); |
| Prototype in: stdlib.h, alloc.h |
| |
| Remarks: Calloc provides access to the C heap memory . Calloc allocates a block of size n items of x size. The block is cleared to 0. |
| |
| |
| |
| |
| |