0

I have seen this asked in different forms, and I have been reading up on it, but I am still confused on how to find the memory used. I have an array it is being pointed to by a pointer the value *ptr = the number of elements in the array. I need the total size of the array and its elements (it is an array of short int and it has 14 elements total). I am confused on how to get this value of memory used by the array + memory used by the elements, would I just use size of and then add the two. This is where I keep running into issues. Can someone point me in the right direction?

  • 2
    The array consists of its elements, without anything extra. – Deduplicator Feb 04 '17 at 17:00
  • 2
    Can you please try to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) and show us? That will make it easier to understand what you mean. Code says more than a thousand pictures. – Some programmer dude Feb 04 '17 at 17:00
  • 1
    A pointer doesn't have any information about the actual size of memory used. Use a `std:vector` intead. – πάντα ῥεῖ Feb 04 '17 at 17:01
  • 1
    array size * sizeof(type). –  Feb 04 '17 at 17:01
  • farhat latrach, will this be right then, because I actually have tried this and I was unsure – Penny Allison Feb 04 '17 at 17:03
  • 1
    Do not use C-style arrays or pointers in C++. Whenever you need an array, use `std::vector` or (if the size is known in advance) `std::array`. – n. m. could be an AI Feb 04 '17 at 17:11
  • You need to remember the size when you created it. Please show some code. – Richard Critten Feb 04 '17 at 17:24
  • The size of the array is the size of the elements. There may be a pointer to the array, but this is not part of the array. There may be memory management bookkeeping at the runtime or operating system level, but you have zero control over this (and it's dangerous to the program to try to control it) so it is best ignored. Point to some of the confusing questions/answers and we can either better explain them (or downvote them into the sewer after a burst of laughter). – user4581301 Feb 04 '17 at 17:43

2 Answers2

6

To get the size in bytes of the array, you would have to calculate it using sizeof(short int) * number_of_elements, where number_of_elements is 14.

Ryan
  • 14,392
  • 8
  • 62
  • 102
0

Instead of raw arrays, e.g., int ar[4], use std::array from <array>. Such array provides bounds checking for debug mode and, unlike raw arrays, can easily be copied and used as a function's argument. It also provides a size() method.

The Techel
  • 918
  • 8
  • 13