Before you learn about the relationship between arrays and pointers, be sure to check these two topics:. An array is a block of sequential data. Let's write a program to print addresses of array elements. There is a difference of 4 bytes between two consecutive elements of array x.

Author:Nikonris Darn
Language:English (Spanish)
Published (Last):4 July 2013
PDF File Size:12.54 Mb
ePub File Size:19.4 Mb
Price:Free* [*Free Regsitration Required]

A pointer is a value that designates the address i. Pointers are variables that hold a memory location. Pointers can reference any data type, even functions. We'll also discuss the relationship of pointers with text strings and the more advanced concept of function pointers. Lines define a structure. Line 8 declares a variable which points to an int , and line 9 declares a variable which points to something with structure MyStruct.

In the following, line 1 declares var1 as a pointer to a long and var2 as a long and not a pointer to a long. In line 2, p3 is declared as a pointer to a pointer to an int. Pointer types are often used as parameters to function calls. The following shows how to declare a function which uses a pointer as an argument.

Since C passes function arguments by value, in order to allow a function to modify a value from the calling routine, a pointer to the value must be passed.

Pointers to structures are also used as function arguments even when nothing in the struct will be modified in the function. This is done to avoid copying the complete contents of the structure onto the stack.

More about pointers as function arguments later. So far we've discussed how to declare pointers. The process of assigning values to pointers is next. Pointers can also be assigned to reference dynamically allocated memory. The malloc and calloc functions are often used to do this. The malloc function returns a pointer to dynamically allocated memory or NULL if unsuccessful. The size of this memory will be appropriately sized to contain the MyStruct structure. The following is an example showing one pointer being assigned to another and of a pointer being assigned a return value from a function.

When returning a pointer from a function, do not return a pointer that points to a value that is local to the function or that is a pointer to a function argument. Pointers to local variables become invalid when the function exits. In the above function, the value returned points to a static variable. Returning a pointer to dynamically allocated memory is also valid.

Here's a short example. There is one more way of dereferencing a pointer, which will be discussed in the following section. When dereferencing a pointer that points to an invalid memory location, an error often occurs which results in the program terminating. The error is often reported as a segmentation error. A common cause of this is failure to initialize a pointer before trying to dereference it.

C is known for giving you just enough rope to hang yourself, and pointer dereferencing is a prime example. You are quite free to write code that accesses memory outside that which you have explicitly requested from the system. And many times, that memory may appear as available to your program due to the vagaries of system memory allocation. However, even if 99 executions allow your program to run without fault, that th execution may be the time when your "memory pilfering" is caught by the system and the program fails.

Be careful to ensure that your pointer offsets are within the bounds of allocated memory! You can assign a value to a void pointer, but you must cast the variable to point to some specified type before you can dereference it. Up to now, we've carefully been avoiding discussing arrays in the context of pointers.

The interaction of pointers and arrays can be confusing but here are two fundamental statements about it:. The first case often is seen to occur when an array is passed as an argument to a function. The function declares the parameter as a pointer, but the actual argument may be the name of an array. The second case often occurs when accessing dynamically allocated memory.

Let's look at examples of each. In the following code, the call to calloc effectively allocates an array of struct MyStruct items. Pointers and array names can pretty much be used interchangeably.

There are exceptions. You cannot assign a new pointer value to an array name. The array name will always point to the first element of the array.

In the function KrazyFunction above, you could however assign a new value to parm1, as it is just a pointer to the first element of myArray.

It is also valid for a function to return a pointer to one of the array elements from an array passed as an argument to a function. A function should never return a pointer to a local variable, even though the compiler will probably not complain. When declaring parameters to functions, declaring an array variable without a size is equivalent to declaring a pointer.

Often this is done to emphasize the fact that the pointer variable will be used in a manner equivalent to an array. Now we're ready to discuss pointer arithmetic. So for instance in the above example where we had the expression secondArray[i]. Note that for addition and subtraction of integers and pointers, the value of the pointer is not adjusted by the integer amount, but is adjusted by the amount multiplied by the size in bytes of the type to which the pointer refers.

One pointer may also be subtracted from another, provided they point to elements of the same array or the position just beyond the end of the array. If you have a pointer that points to an element of an array, the index of the element is the result when the array name is subtracted from the pointer.

Here's an example. You may be wondering how pointers and multidimensional arrays interact. Let's look at this a bit in detail. Suppose A is declared as a two dimensional array of floats float A[D1][D2]; and that pf is declared a pointer to a float. The elements of the array are stored in row-major order. Let's look at a slightly different problem. We want to have a two dimensional array, but we don't need to have all the rows the same length.

What we do is declare an array of pointers. The second line below declares A as an array of pointers. Each pointer points to a float. Here's some applicable code:. We also note here something curious about array indexing.

Suppose myArray is an array and idx is an integer value. The expression myArray[idx] is equivalent to idx[myArray]. These turn out to be the same, since the addition is commutative.

Pointers can be used with preincrement or post decrement, which is sometimes done within a loop, as in the following example. The increment and decrement applies to the pointer, not to the object to which the pointer refers. Often we need to invoke a function with an argument that is itself a pointer.

In many instances, the variable is itself a parameter for the current function and may be a pointer to some type of structure.

The ampersand character is not needed in this circumstance to obtain a pointer value, as the variable is itself a pointer. In the example below, the variable pStruct , a pointer, is a parameter to function FunctTwo , and is passed as an argument to FunctOne.

The second parameter to FunctOne is an int. The third parameter to function FunctOne is a pointer to a long. Since pAA is itself a pointer to a long, no ampersand is needed when it is used as the third argument to the function. Most C implementations come with a standard library of functions for manipulating strings.

Many of the more commonly used functions expect the strings to be null terminated strings of characters. To use these functions requires the inclusion of the standard C header file "string. The variable myFormat can be viewed as an array of 21 characters. You can also initialize the individual characters of the array as follows:.

The initialization of an especially long string can be split across lines of source code as follows. C also allows you to create pointers to functions.

Pointers to functions syntax can get rather messy. As an example of this, consider the following functions:. Declaring a typedef to a function pointer generally clarifies the code. Note that DoSomethingNice really doesn't know anything about what dataPointer refers to. Some implementations may require specifically casting the argument to the MyFunctionType type, even though the function signature exacly matches that of the typedef. Function pointers can be useful for implementing a form of polymorphism in C.

First one declares a structure having as elements function pointers for the various operations to that can be specified polymorphically. A second base object structure containing a pointer to the previous structure is also declared. A class is defined by extending the second structure with the data specific for the class, and static variable of the type of the first structure, containing the addresses of the functions that are associated with the class. A similar mechanism can also be used for implementing a state machine in C.

A structure is defined which contains function pointers for handling events that may occur within state, and for functions to be invoked upon entry to and exit from the state.


C Call by Reference: Using pointers

To accept these addresses in the function definition, we can use pointers. It's because pointers are used to store addresses. Let's take an example:. Hence, num1 and num2 are also swapped. Notice that, swap is not returning anything; its return type is void. We then passed the pointer p to the addOne function.


Relationship Between Arrays and Pointers

C Pointer Basics. Please wait while the activity loads. If this activity does not load, try refreshing your browser. Also, this page requires javascript. Please visit using a browser with javascript enabled. If loading fails, click here to try again.


C Programming/Pointers and arrays

In the previous C programming language tutorial we looked at the fundamentals of pointers. In this C tutorial we will look at some specifics of pointers. Before you can use a pointer in for instance a printf statement, you have to initialize the pointer. The following example will not initialize the pointer:. However, we did not initialize the pointer. In this case the pointer contains a random address or 0. The result of this program is a segmentation fault, some other run-time error or the random address is printed.


C library function - memset()

We already know that a pointer points to a location in memory and thus used to store the address of variables. So, when we define a pointer to pointer. The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double pointers. How to declare a pointer to pointer in C? Declaring Pointer to Pointer is similar to declaring pointer in C.

Related Articles