Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between pointer to a new element and new array? [duplicate]

Tags:

c++

In C++ is there any difference between the pointers p and q in the below code?

int* p = new int;
int* q = new int[5];

I understand that one allots new memory for a single int and the second allots memory for an array of 5 ints, but fundamentally is there any difference between a pointer pointing to a single int and one pointing to an array of ints?

I got this doubt because I read that one must use delete[] q to free up memory pointed to by q but just delete p for the single int pointed to by p. What would happen if I used delete q?

like image 914
strider0160 Avatar asked May 20 '19 12:05

strider0160


People also ask

What is difference between pointer to array and array of pointers?

A user creates a pointer for storing the address of any given array. A user creates an array of pointers that basically acts as an array of multiple pointer variables. It is alternatively known as an array pointer. These are alternatively known as pointer arrays.

What is the difference between an array and a pointer?

An array is a collection of elements of similar data type whereas the pointer is a variable that stores the address of another variable. An array size decides the number of variables it can store whereas; a pointer variable can store the address of only one variable in it.

What is the difference between a pointer and an array in C?

Array in C is used to store elements of same types whereas Pointers are address varibles which stores the address of a variable. Now array variable is also having a address which can be pointed by a pointer and array can be navigated using pointer.

What is the relationship between an array name and a pointer?

The only difference between an array name and a normal pointer variable is that an array name always points to a specific address, which is the starting address of the array. Pointers are flexible and can point to wherever you want them to point.


2 Answers

The pointers themselves are completely indistinguishable. That's why you must remember to match new/delete and new[]/delete[].

Mismatching them triggers undefined behaviour.

like image 52
Quentin Avatar answered Sep 28 '22 16:09

Quentin


When using new [] some c++ implementations will track the size of the allocation of the array in the address before the pointer returned. This is an implementation detail not defined by the standard.

The following answer describes this possible implementation in a little more detail: How could pairing new[] with delete possibly lead to memory leak only?

You must always match new with delete and new [] with delete []. It is Undefined Behavior to mix these.

like image 41
drescherjm Avatar answered Sep 28 '22 16:09

drescherjm