Home  >  Article  >  Backend Development  >  Can You Determine the Size of an Array Allocated with `new T[]` in C ?

Can You Determine the Size of an Array Allocated with `new T[]` in C ?

DDD
DDDOriginal
2024-11-08 05:39:01348browse

Can You Determine the Size of an Array Allocated with `new T[]` in C  ?

Can Arrays Allocated with new T[] Disclose Their Size?

Unlike its counterpart delete[], which inherently knows the size of the allocated array, C lacks a mechanism to programmatically ascertain the size of an array created using new T[].

Delving into the Distinction

The crux of this disparity lies in the intrinsic nature of delete[]. During compilation, the size of the array is meticulously preserved by the runtime or the operating system's memory manager. However, this information remains inaccessible to the compiler. Conversely, sizeof(), an operand to the compiler rather than a genuine function, cannot determine the size of dynamically allocated arrays as their extent is uncertain at compile time.

Illustrative Example

Consider this code sample:

int *arr = new int[256];
int *p = &arr[100];
printf("Size: %d\n", sizeof(p));

Here, the compiler confronts a perplexing dilemma: how to determine the size of p. An array's pointers lack inherent knowledge of the start or end of the allocated memory block. They may indicate the beginning of the block, a specific element within it, or even an arbitrary location.

Inherent Limitations

C and C arrays, unlike first-class objects, degenerate into pointers. The compiler and program alike are unaware if the pointer identifies the start of a new block, an individual object, or an intermediate address.

This design choice stems from the delegated nature of memory management in C and C , leaving it to the programmer and operating system. New and delete implementations vary greatly across platforms and scenarios, precluding standardization within the C standard.

The above is the detailed content of Can You Determine the Size of an Array Allocated with `new T[]` in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn