Pointers and arrays in cpp

C++ Pointers and Arrays

In C++, Pointers are variables that hold addresses of other variables. Not only can a pointer store the address of a single variable, it can also store the address of cells of an array.

int *ptr; int arr[5]; // store the address of the first // element of arr in ptr ptr = arr;

Here, ptr is a pointer variable while arr is an int array. The code ptr = arr; stores the address of the first element of the array in variable ptr .

Notice that we have used arr instead of &arr[0] . This is because both are the same. So, the code below is the same as the code above.

The addresses for the rest of the array elements are given by &arr[1] , &arr[2] , &arr[3] , and &arr[4] .

Point to Every Array Elements

Suppose we need to point to the fourth element of the array using the same pointer ptr .

Here, if ptr points to the first element in the above example then ptr + 3 will point to the fourth element. For example,

int *ptr; int arr[5]; ptr = arr; ptr + 1 is equivalent to &arr[1]; ptr + 2 is equivalent to &arr[2]; ptr + 3 is equivalent to &arr[3]; ptr + 4 is equivalent to &arr[4];

Similarly, we can access the elements using the single pointer. For example,

// use dereference operator *ptr == arr[0]; *(ptr + 1) is equivalent to arr[1]; *(ptr + 2) is equivalent to arr[2]; *(ptr + 3) is equivalent to arr[3]; *(ptr + 4) is equivalent to arr[4];

Suppose if we have initialized ptr = &arr[2]; then

ptr - 2 is equivalent to &arr[0]; ptr - 1 is equivalent to &arr[1]; ptr + 1 is equivalent to &arr[3]; ptr + 2 is equivalent to &arr[4];

Working of C++ Pointers with Arrays

Note: The address between ptr and ptr + 1 differs by 4 bytes. It is because ptr is a pointer to an int data. And, the size of int is 4 bytes in a 64-bit operating system.

Similarly, if pointer ptr is pointing to char type data, then the address between ptr and ptr + 1 is 1 byte. It is because the size of a character is 1 byte.

Example 1: C++ Pointers and Arrays

// C++ Program to display address of each element of an array #include using namespace std; int main() < float arr[3]; // declare pointer variable float *ptr; cout // ptr = &arr[0] ptr = arr; coutOutput

Displaying address using arrays: &arr[0] = 0x61fef0 &arr[1] = 0x61fef4 &arr[2] = 0x61fef8 Displaying address using pointers: ptr + 0 = 0x61fef0 ptr + 1 = 0x61fef4 ptr + 2 = 0x61fef8

In the above program, we first simply printed the addresses of the array elements without using the pointer variable ptr .

Then, we used the pointer ptr to point to the address of a[0] , ptr + 1 to point to the address of a[1] , and so on.

In most contexts, array names decay to pointers. In simple words, array names are converted to pointers. That's the reason why we can use pointers to access elements of arrays.

However, we should remember that pointers and arrays are not the same.

There are a few cases where array names don't decay to pointers. To learn more, visit: When does array name doesn't decay into a pointer?

Example 2: Array name used as pointer

// C++ Program to insert and display data entered by using pointer notation. #include using namespace std; int main() < float arr[5]; // Insert data using pointer notation cout > *(arr + i) ; > // Display data using pointer notation cout return 0; >
Enter 5 numbers: 2.5 3.5 4.5 5 2 Displaying data: 2.5 3.5 4.5 5 2

    We first used the pointer notation to store the numbers entered by the user into the array arr .

Источник

11.7 — Pointers and arrays

11.7 — Pointers and arrays

Pointers and arrays are intrinsically related in C++.

In a previous lesson, you learned how to define a fixed array:

int array[5]< 9, 7, 5, 3, 1 >; // declare a fixed array of 5 integers

To us, the above is an array of 5 integers, but to the compiler, array is a variable of type int[5]. We know what the values of array[0], array[1], array[2], array[3], and array[4] are (9, 7, 5, 3, and 1 respectively).

In all but two cases (which we’ll cover below), when a fixed array is used in an expression, the fixed array will decay (be implicitly converted) into a pointer that points to the first element of the array. You can see this in the following program:

#include int main() < int array[5]< 9, 7, 5, 3, 1 >; // print address of the array's first element std::cout 

On the author’s machine, this printed:

Element 0 has address: 0042FD5C The array decays to a pointer holding address: 0042FD5C

It’s a common fallacy in C++ to believe an array and a pointer to the array are identical. They’re not. In the above case, array is of type “int[5]”, and its “value” is the array elements themselves. A pointer to the array would be of type “int*”, and its value would be the address of the first element of the array.

We’ll see where this makes a difference shortly.

All elements of the array can still be accessed through the pointer (we’ll see how this works in the next lesson), but information derived from the array’s type (such as how long the array is) can not be accessed from the pointer.

However, this also effectively allows us to treat fixed arrays and pointers identically in most cases.

For example, we can dereference the array to get the value of the first element:

int array[5]< 9, 7, 5, 3, 1 >; // Deferencing an array returns the first element (element 0) std::cout ; // C-style string (also an array) std::cout 

Note that we’re not actually dereferencing the array itself. The array (of type int[5]) gets implicitly converted into a pointer (of type int*), and we dereference the pointer to get the value at the memory address the pointer is holding (the value of the first element of the array).

We can also assign or initialize a pointer to point at the array:

#include int main() < int array[5]< 9, 7, 5, 3, 1 >; std::cout ; std::cout 

This works because the array decays into a pointer of type int, and our pointer (also of type int) has the same type.

Differences between pointers and fixed arrays

There are a few cases where the difference in typing between fixed arrays and pointers makes a difference. These help illustrate that a fixed array and a pointer are not the same.

The primary difference occurs when using the sizeof() operator. When used on a fixed array, sizeof returns the size of the entire array (array length * element size). When used on a pointer, sizeof returns the size of the pointer (in bytes). The following program illustrates this:

#include int main() < int array[5]< 9, 7, 5, 3, 1 >; std::cout ; std::cout 

Assuming pointers are 4 bytes, this program prints:

A fixed array knows how long the array it is pointing to is. A pointer to the array does not.

The second difference occurs when using the address-of operator (&). Taking the address of a pointer yields the memory address of the pointer variable. Taking the address of the array returns a pointer to the entire array. This pointer also points to the first element of the array, but the type information is different (in the above example, the type of &array is int(*)[5] ). It’s unlikely you’ll ever need to use this.

#include int main() < int array[5]< 9, 7, 5, 3, 1 >; std::cout ; std::cout // h/t to reader PacMan for this example

Revisiting passing fixed arrays to functions

Back in lesson 11.2 -- Arrays (Part II), we mentioned that because copying large arrays can be very expensive, C++ does not copy an array when an array is passed into a function. When passing an array as an argument to a function, a fixed array decays into a pointer, and the pointer is passed to the function:

#include void printSize(int* array) < // array is treated as a pointer here std::cout int main() < int array[]< 1, 1, 2, 3, 5, 8, 13, 21 >; std::cout 

Assuming pointers are 4 bytes, this prints:

Note that this happens even if the parameter is declared as a fixed array:

#include // C++ will implicitly convert parameter array[] to *array void printSize(int array[]) < // array is treated as a pointer here, not a fixed array std::cout int main() < int array[]< 1, 1, 2, 3, 5, 8, 13, 21 >; std::cout 

Assuming pointers are 4 bytes, this prints:

In the above example, C++ implicitly converts parameters using the array syntax ([]) to the pointer syntax (*). That means the following two function declarations are identical:

void printSize(int array[]); void printSize(int* array);

Some programmers prefer using the [] syntax because it makes it clear that the function is expecting an array, not just a pointer to a value. However, in most cases, because the pointer doesn’t know how large the array is, you’ll need to pass in the array size as a separate parameter anyway (strings being an exception because they’re null terminated).

We recommend using the pointer syntax, because it makes it clear that the parameter is being treated as a pointer, not a fixed array, and that certain operations, such as sizeof(), will operate as if the parameter is a pointer.

Favor the pointer syntax (*) over the array syntax ([]) for array function parameters.

An intro to pass by address

The fact that arrays decay into pointers when passed to a function explains the underlying reason why changing an array in a function changes the actual array argument passed in. Consider the following example:

#include // parameter ptr contains a copy of the array's address void changeArray(int* ptr) < *ptr = 5; // so changing an array element changes the _actual_ array >int main() < int array[]< 1, 1, 2, 3, 5, 8, 13, 21 >; std::cout
Element 0 has value: 1 Element 0 has value: 5

When changeArray() is called, array decays into a pointer, and the value of that pointer (the memory address of the first element of the array) is copied into the ptr parameter of function changeArray(). Although the value in ptr is a copy of the address of the array, ptr still points at the actual array (not a copy!). Consequently, when dereferencing ptr, the element accessed is the actual first element of the array!

Astute readers will note this phenomenon works with pointers to non-array values as well.

Other times arrays don’t decay

It is worth noting that arrays that are part of structs or classes do not decay when the whole struct or class is passed to a function. This yields a useful way to prevent decay if desired, and will be valuable later when we write classes that utilize arrays.

Arrays passed by reference also will not decay.

In the next lesson, we’ll take a look at pointer arithmetic, and talk about how array indexing actually works.

Источник

Pointers vs Array in C/C++

An array is the collection of multiple items of the same type stored in contiguous memory locations. While declaring Arrays, the size should be mentioned and their indexing starts from 0 in C/C++.

Array in C

The position of each element can be calculated by adding an offset to the base value, i.e., the memory location of the first element of the array.

C

C++

A pointer is the symbolic representation of addresses. It stores the address of variables or memory location. Pointers enable programmers to create and manipulate dynamic data structures. Variables can be of type int, array, char, function, or any other pointer.

C

C++

Difference Between Arrays and Pointers in C/C++

The pointer can be used to access the array elements, accessing the whole array using pointer arithmetic, makes the accessing faster. The main difference between Array and Pointers is the fixed size of the memory block. When Arrays are created the fixed size of the memory block is allocated. But with Pointers the memory is dynamically allocated. There are some other differences between an array and a pointer which are discussed below in the table.

S. No. Array Pointer
1. Arrays are declared as type var_name[size]; Pointers are declared as type * var_name;
2. Collection of elements of similar data type. Store the address of another variable.
3. The array can be initialized at the time of definition. Pointers cannot be initialized at definition.
4. An array can decide the number of elements it can store. The pointer can store the address of only one variable.
5. Arrays are allocated at compile time. Pointers are allocated at run-time.
6. Memory allocation is in sequence. Memory allocation is random.
7. Arrays are static in nature i.e. they cannot be resized according to the user requirements. Pointers are dynamic in nature i.e. memory allocated can be resized later.
8. An array of pointers can be generated. A pointer to an array can be generated.
9. Java Support the concept of an array. Java Does not support pointers.
10. An array is a group of elements. Pointer is not a group of elements.

Источник

Читайте также:  Найти сумму четных чисел числа питон
Оцените статью