Initialize the dynamically allocated array, sizeof Length

Source: Internet
Author: User

When writing a Data Structure experiment today, an array is dynamically allocated:

Bool * vis = new bool [N];

Then initialize the VIS array:

Memset (VIS, 0, sizeof (VIS ));

As a result, the experiment results are always merged.

The cause is eventually discovered:

VIS is a pointer, so the result of sizeof (VIS) is 4. vis only points to the first address of the memory allocated by the heap. It is different from directly opening a static array (I don't know why), and the pointer size occupies 4, therefore, sizeof (VIS) always returns 4 results.

Therefore, the correct method for initializing the Dynamic Allocation array for memset is:

Type * vis = new type [N]; memset (VIS, 0, N * sizeof (type ));

Later, Baidu went to more details: Exploring the differences between C/C ++ array names and pointers

In short, arrays are also a data structure!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.