Getting sizeof a member of the class in C++ - c++

I've built a class called IntSet. My problem is that i dont want to storage another element that is the maximum amount of elements i want to introduce in elem array. So, in add method or any other method, i want to find out the max size i've allocated in the IntSet (int dim_max) constructor using this operation :
int n = sizeof(elem) / sizeof(*elem); //or sizeof(elem) / sizeof(int);
cout << "N is = " << n;
However, this doesnt work, everytime n is 1, even if i allocate elem = new int[dim_max];, where dim_max is a variable i read from the keyboard and it's much bigger than 1. Here is the code :
#include <iostream>
using namespace std;
class IntSet{
int *elem;
int dim;
public:
IntSet (int dim_max) {
dim = -1;
elem = new int[dim_max];
}
void add(int new_el) {
int n = sizeof(elem) / sizeof(int);
cout << "N is =" << n;
for(int i = 0; i < n; i++) {
if(elem[i] == new_el) {
cout << "It's already there !";
return;
}
}
dim++;
if(dim == n) {
elem = (int*)realloc(elem, sizeof(int) * (n + 1));
global_var++;
}
elem[dim] = new_el;
}
};

The sizeof operator works on the types at compile time. Since elem is an int*, sizeof(elem) is the same as sizeof(int*). And *elem is an int, so sizeof(*elem) is sizeof(int).
So in the end, your formula is equivalent to sizeof(int*)/sizeof(int), regardless of what you put in elem. There is no standard way to find out the number of elements of the array that that was allocated for a pointer.
For your purpose, you either must either keep track of dim_max in your class, or, better, replace the use of pointers and arrays with the nicer vector.
Vectors offer a size() function, and allow to easily add new element dynamically at the end using push_back(). Maybe it could interest you as well: there is also a set container in the standard library.

elem is a pointer and sizeof(ptr) is always fixed. On 32-bit machine sizeof pointer is 32 bits ( 4 bytes), while on 64 bit machine it's 8 byte. Regardless of what data type they are pointing to, they have fixed size.
So, the computation you are doing sizeof(elem)/sizeof(*elem) will always yield 1 as it's matching with sizeof(int). This would work if elem is an array with predetermined size.
To keep track of current size, you need to have another variable.
Another thing is don't mix new and realloc. Always use new as you are using C++.

It is because, elem is a pointer. So, every time you are doing sizeof(elem) or sizeof(*elem); will give you the size of data type & pointer respectively.
If you havent used dynamic allocation, then answer would be OK.
I would suggest you to use STL container or store max size as a data member.

First thing first you divide two non double value so the result is not what you expect
12/8 is 1.
sizeof a pointer depending on the architecture is 8 or 4.
What you think is sizeof returning the size of array which is only the case for automatic arrays not dynamic ones.

Related

Dynamic array of Linear search funcion implementation

Need to implement a function
int* linearSearch(int* array, int num);
That gets a fixed size array of integers with a number and return an array with indices to the occurrences of the searched number.
For example array={3,4,5,3,6,8,7,8,3,5} & num=5 will return occArray={2,9}.
I've implemented it in c++ with a main function to check the output
#include <iostream>
using namespace std;
int* linearSearch(int* array, int num);
int main()
{
int array[] = {3,4,5,3,6,8,7,8,3,5}, num=5;
int* occArray = linearSearch(array, num);
int i = sizeof(occArray)/sizeof(occArray[0]);
while (i>0) {
std::cout<<occArray[i]<<" ";
i--;
}
}
int* linearSearch(int* array, int num)
{
int *occArray= new int[];
for (int i = 0,j = 0; i < sizeof(array) / sizeof(array[0]); i++) {
if (array[i] == num) {
occArray[j] = i;
j++;
}
}
return occArray;
}
I think the logic is fine but I have a syntax problems with creating a dynamic cell for occArray
Also a neater implantation with std::vector will be welcomed
Thank You
At very first I join in the std::vector recommendation in the question's comments (pass it as const reference to avoid unnecessary copy!), that solves all of your issues:
std::vector<size_t> linearSearch(std::vector<int> const& array, int value)
{
std::vector<size_t> occurrences;
// to prevent unnecessary re-allocations, which are expensive,
// one should reserve sufficient space in advance
occurrences.reserve(array.size());
// if you expect only few occurrences you might reserve a bit less,
// maybe half or quarter of array's size, then in general you use
// less memory but in few cases you still re-allocate
for(auto i = array.begin(); i != array.end(); ++i)
{
if(*i == value)
{
// as using iterators, need to calculate the distance:
occurrences.push_back(i - array.begin());
}
}
return occurences;
}
Alternatively you could iterate with a size_t i variable from 0 to array.size(), compare array[i] == value and push_back(i); – that's equivalent, so select whichever you like better...
If you cannot use std::vector for whatever reason you need to be aware of a few issues:
You indeed can get the length of an array by sizeof(array)/sizeof(*array) – but that only works as long as you have direct access to that array. In most other cases (including passing them to functions) arrays decay to pointers and these do not retain any size information, thus this trick won't work any more, you'd always get sizeOfPointer/sizeOfUnderlyingType, on typical modern 64-bit hardware that would be 8/4 = 2 for int* – no matter how long the array originally was.
So you need to pass the size of the array in an additional parameter, e.g.:
size_t* linearSearch
(
int* array,
size_t number, // of elements in the array
int value // to search for
);
Similarly you need to return the number of occurrences of the searched value by some means. There are several options for:
Turn num into a reference (size_t& num), then you can modify it inside the function and the change gets visible outside. Usage of the function get's a bit inconvenient, though, as you need to explicitly define a variable for:
size_t num = sizeof(array)/sizeof(*array);
auto occurrences = linearSearch(array, num, 7);
Append a sentinel value to the array, which might be the array size or probably better maximum value for size_t – with all the disadvantages you have with C strings as well (mainly having to iterate over the result array to detect the number of occurences).
Prepend the number of occurrences to the array – somehow ugly as well as you mix different kind of information into one and the same array.
Return result pointer and size in a custom struct of yours or in e.g. a std::pair<size_t, size_t*>. You could even use that in a structured binding expression when calling the function:
auto [num, occurences] = linearSearch(array, sizeof(array)/sizeof(*array), 7);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// here the trick yet works provided the array is declared above the call, too,
// as is in your example
Option 4 would be my personal recommendation out of these.
Side note: I switched to size_t for return values as negative indices into an array are meaningless anyway (unless you intend to use these as sentinel values, e. g. -1 for end of occurrences in option 2).

Size of dynamic array or loop through it without knowing size

Like in title, can I somehow get size of dynamic allocated array (I can't keep it separately), or somehow loop through this array without using it's size?
int *ar=new int[x]; //x-size of array, I don't know it in the beggining,
P.S. If I wanted to use std::vector, I wouldn't ask about it, so don't tell me to use it :)
A std::vector is designed for this.
If you can't use a std::vector I can see a couple of options.
1) Use an array terminator.
If your array should only contain positive numbers (for example) or numbers within a given range then you can use an illegal value (eg -1) as an array terminator.
for(int* i = arr; *i != -1; ++i)
{
// do something with *i
}
2) Embed the length in the array.
For a numeric array you could, by convention, store its length in the first element.
for(int i = 0; i < arr[0]; ++i)
{
// do something with arr[i + 1]
}
If you want to store the size your dynamic array inside it, well, just do so:
#include <iostream>
#include <cstdint>
#include <cstddef>
using std::size_t;
struct head_t { size_t size; int data[]; };
int main() {
head_t* h = static_cast<head_t*>(::operator new(sizeof(head_t) + 10 * sizeof(int)));
h->size = 10;
int* my_10_ints = h->data;
// Oh noez! I forgot 10!
size_t what_was_10_again = static_cast<head_t*>(static_cast<void*>(my_10_ints) - offsetof(head_t, data))->size;
::std::cout << what_was_10_again << "\n";
::operator delete(static_cast<void*>(my_10_ints) - offsetof(head_t, data));
}
You can even put that functionality in a libraryesque set of functions! Oh, and once you do that you realize you could just have an unordered_map that maps pointers to sizes. But that would be like using vector: Totally boring.
No. That's one reason everybody uses containers. If std::vector doesn't please you, you can make a container of your own.
Edit: Since dynamic array size is determined at runtime, someone must store the size somewhere (unless you're willing to use a sentry value). Not even the compiler can help, because the size is determined in runtime.

Can I determine the size/length of an array in C++ without having to hardcode it?

I am basically looking for some sort of "dynamic" way of passing the size/length of an array to a function.
I have tried:
void printArray(int arrayName[])
{
for(int i = 0 ; i < sizeof(arrayName); ++i)
{
cout << arrayName[i] << ' ';
}
}
But I realized it only considers its bytesize and not how many elements are on the array.
And also:
void printArray(int *arrayName)
{
while (*arrayName)
{
cout << *arrayName << ' ';
*arrayName++;
}
}
This has at least printed me everything but more than what I expected, so it doesn't actually work how I want it to.
I reckon it is because I don't exactly tell it how big I need it to be so it plays it "safe" and throws me some big size and eventually starts printing me very odd integers after my last element in the array.
So I finally got this work around, yet I believe there is something better out there!:
void printArray(int *arrayName)
{
while (*arrayName)
{
if (*arrayName == -858993460)
{
break;
}
cout << *arrayName << ' ';
*arrayName++;
}
cout << '\n';
}
After running the program a few times I realized the value after the last element of the array that I have input is always: -858993460, so I made it break the while loop once this value is encountered.
include <iostream>
include <conio.h>
using namespace std;
// functions prototypes
void printArray (int arrayName[], int lengthArray);
// global variables
//main
int main ()
{
int firstArray[] = {5, 10, 15};
int secondArray[] = {2, 4, 6, 8, 10};
printArray (firstArray,3);
printArray (secondArray,5);
// end of program
_getch();
return 0;
}
// functions definitions
void printArray(int arrayName[], int lengthArray)
{
for (int i=0; i<lengthArray; i++)
{
cout << arrayName[i] << " ";
}
cout << "\n";
}
Thank you very much.
TL;DR answer: use std::vector.
But I realized it [sizeof()] only considers its bytesize and not how many elements are on the array.
That wouldn't be a problem in itself: you could still get the size of the array using sizeof(array) / sizeof(array[0]), but the problem is that when passed to a function, arrays decay into a pointer to their first element, so all you can get is sizeof(T *) (T being the type of an element in the array).
About *arrayName++:
This has at least printed me everything but more than what I expected
I don't even understand what inspired you to calculate the size of the array in this way. All that this code does is incrementing the first object in the array until it's zero.
After running the program a few times I realized the value after the last element of the array that I have input is always: -858993460
That's a terrible assumption and it also relies on undefined behavior. You can't really be sure what's in the memory after the first element of your array, you should not even be accessing it.
Basically, in C++, if you want to know the size of a raw array from within a function, then you have to keep track of it manually (e. g. adding an extra size_t size argument), because of the way arrays are passed to functions (remember, they "decay into" a pointer). If you want something more flexible, consider using std::vector<int> (or whatever type of objects you want to store) from the C++ standard library -- it has a size() method, which does exactly what you want.
1st try
When arrays are passed into functions they decay to pointers. Normally, using sizeof on an array would give you its size in bytes which you could then divide by the size in bytes of each element and get the number of elements. But now, since you have a pointer instead of an array, calling sizeof just gives you the size of the pointer (usually 4 or 8 bytes), not the array itself and that's why this fails.
2nd try
The while loop in this example assumes that your array ends with a zero and that's very bad (unless you really did use a zero as a terminator like null-terminated strings for example do). If your array doesn't end with a zero you might be accessing memory that isn't yours and therefore invoking undefined behavior. Another thing that could happen is that your array has a zero element in the middle which would then only print the first few elements.
3rd try
This special value you found lurking at the end of your array can change any time. This value just happened to be there at this point and it might be different another time so hardcoding it like this is very dangerous because again, you could end up accessing memory that isn't yours.
Your final code
This code is correct and passing the length of the array along with the array itself is something commonly done (especially in APIs written in C). This code shouldn't cause any problems as long as you don't pass a length that's actually bigger than the real length of the array and this can happen sometimes so it is also error prone.
Another solution
Another solution would be to use std::vector, a container which along with keeping track of its size, also allows you to add as many elements as you want, i.e. the size doesn't need to be known at runtime. So you could do something like this:
#include <iostream>
#include <vector>
#include <cstddef>
void print_vec(const std::vector<int>& v)
{
std::size_t len = v.size();
for (std::size_t i = 0; i < len; ++i)
{
std::cout << v[i] << std::endl;
}
}
int main()
{
std::vector<int> elements;
elements.push_back(5);
elements.push_back(4);
elements.push_back(3);
elements.push_back(2);
elements.push_back(1);
print_vec(elements);
return 0;
}
Useful links worth checking out
Undefined behavior: Undefined, unspecified and implementation-defined behavior
Array decay: What is array decaying?
std::vector: http://en.cppreference.com/w/cpp/container/vector
As all the other answers say, you should use std::vector or, as you already did, pass the number of elements of the array to the printing function.
Another way to do is is by putting a sentinel element (a value you are sure it won't be inside the array) at the end of the array. In the printing function you then cycle through the elements and when you find the sentinel you stop.
A possible solution: you can use a template to deduce the array length:
template <typename T, int N>
int array_length(T (&array)[N]) {
return N;
}
Note that you have to do this before the array decays to a pointer, but you can use the technique directly or in a wrapper.
For example, if you don't mind rolling your own array wrapper:
template <typename T>
struct array {
T *a_;
int n_;
template <int N> array(T (&a)[N]) : a_(a), n_(N) {}
};
You can do this:
void printArray(array<int> a)
{
for (int i = 0 ; i < a.n_; ++i)
cout << a.a_[i] << ' ';
}
and call it like
int firstArray[] = {5, 10, 15};
int secondArray[] = {2, 4, 6, 8, 10};
printArray (firstArray);
printArray (secondArray);
The key is that the templated constructor isn't explicit so your array can be converted to an instance, capturing the size, before decaying to a pointer.
NB. The wrapper shown isn't suitable for owning dynamically-sized arrays, only for handling statically-sized arrays conveniently. It's also missing various operators and a default constructor, for brevity. In general, prefer std::vector or std::array instead for general use.
... OP's own attempts are completely addressed elsewhere ...
Using the -858993460 value is highly unreliable and, in fact, incorrect.
You can pass a length of array in two ways: pass an additional parameter (say size_t length) to your function, or put a special value to the end of array. The first way is preferred, but the second is used, for example, for passing strings by char*.
In C/C++ it's not possible to know the size of an array at runtime. You might consider using an std::vector class if you need that, and it has other advantages as well.
When you pass the length of the array to printArray, you can use sizeof(array) / sizeof(array[0]), which is to say the size in bytes of the whole array divided by the size in bytes of a single element gives you the size in elements of the array itself.
More to the point, in C++ you may find it to your advantage to learn about std::vector and std::array and prefer these over raw arrays—unless of course you’re doing a homework assignment that requires you to learn about raw arrays. The size() member function will give you the number of elements in a vector.
In C/C++, native arrays degrade to pointers as soon as they are passed to functions. As such, the "length" parameter has to be passed as a parameter for the function.
C++ offers the std::vector collection class. Make sure when you pass it to a function, you pass it by reference or by pointer (to avoid making a copy of the array as it's passed).
#include <vector>
#include <string>
void printArray(std::vector<std::string> &arrayName)
{
size_t length = arrayName.size();
for(size_t i = 0 ; i < length; ++i)
{
cout << arrayName[i] << ' ';
}
}
int main()
{
std::vector<std::string> arrayOfNames;
arrayOfNames.push_back(std::string("Stack"));
arrayOfNames.push_back(std::string("Overflow"));
printArray(arrayOfNames);
...
}

c++ creating a subarray from a duplicate array

here is my code and im not allowed to use a loop in the subarray function im pretty confused maybe someone can point me in the right direction i feel like im almost there..
int *duplicateArray(int *arr, int size)
{
int *newArray;
if (size<=0)
return NULL;
newArray = new int[size];
for (int index=0;index<size;index++)
newArray[index]=arr[index];
return newArray;
}
int* subArray(int *sub, int start, int length)
{
int aa[10]={1,2,3,4,5,6,7,8,9,10};
int *dup;
dup = aa;
duplicateArray(dup,10);
return dup;
}
int main()
{ cout << "Testing subArray: " << endl
<< "Expected result: 5, 6, 7, 8 " << endl;
int *subArr;
int start = 5;
subArr = subArray(subArr, 5,4);
for (int index = start; index<10; index++)
cout << subArr[index];
delete [] subArr;
subArr = 0;
So, since this is homework, I'm going to avoid posting a solution directly. You say that;
im not allowed to use a loop in the subarray function
Yet, currently, subArray calls duplicateArray, which uses a loop. This seems to be in conflict with the spirit of the requirement.
Since you haven't said otherwise, I'm assuming that subArray should duplicate the contents of its argument between start and the end. So, what do we know?
We know that the size of the returned array should be length - start elements. We also know (well, perhaps) that a function named memcpy exists which allows you to copy a block of bytes from one place to another (assuming they do not overlap).
(note that I am suggesting memcpy here because we are dealing with POD types (Plain Old Data) and because I doubt your class has delved into the STL. In the future you will be better served by something like std::copy(), but for now this is ok)
So, in order, we need to:
Declare a new array to return with length - start elements. You must dynamically allocate this array! Currently you are returning a pointer to a locally declared array. That pointer becomes invalid as soon as the function returns.
Copy length - start elements (elements, not bytes! Make sure to take into account the number of elements as well as the size of an individual element) from sub + start into this new array.
Return the new array (pointer really).
If I have somehow violated the requirements or intent of your assignment then you need to elaborate on your problem for me. Currently there is not much to go on.

Arrays and pointers in a template

I am attempting to write a template/class that has a few functions, but I'm running into what seems like a rather newbie problem. I have a simple insert function and a display values function, however whenever I attempt to display the value, I always receive what looks like a memory address(but I have no idea), but I would like to receive the value stored (in this particular example, the int 2). I'm not sure how to dereference that to a value, or if I'm just completely messing up. I know that vectors are a better alternative, however I need to use an array in this implementation - and honestly I would like to gain a more thorough understanding of the code and what's going on. Any help as to how to accomplish this task would be greatly appreciated.
Example Output (running the program in the same way every time):
003358C0
001A58C0
007158C0
Code:
#include <iostream>
using namespace std;
template <typename Comparable>
class Collection
{
public: Collection() {
currentSize = 0;
count = 0;
}
Comparable * values;
int currentSize; // internal counter for the number of elements stored
void insert(Comparable value) {
currentSize++;
// temparray below is used as a way to increase the size of the
// values array each time the insert function is called
Comparable * temparray = new Comparable[currentSize];
memcpy(temparray,values,sizeof values);
// Not sure if the commented section below is necessary,
// but either way it doesn't run the way I intended
temparray[currentSize/* * (sizeof Comparable) */] = value;
values = temparray;
}
void displayValues() {
for (int i = 0; i < currentSize; i++) {
cout << values[i] << endl;
}
}
};
int main()
{
Collection<int> test;
int inserter = 2;
test.insert(inserter);
test.displayValues();
cin.get();
return 0;
}
Well, if you insist, you can write and debug your own limited version of std::vector.
First, don't memcpy from an uninitialized pointer. Set values to new Comparable[0] in the constructor.
Second, memcpy the right number of bytes: (currentSize-1)*sizeof(Comparable).
Third, don't memcpy at all. That assumes that Comparable types can all be copied byte-by-byte, which is a severe limitation in C++. Instead:
EDIT: changed uninitialized_copy to copy:
std::copy(values, values + currentSize - 1, temparray);
Fourth, delete the old array when it's no longer in use:
delete [] values;
Fifth, unless the code is going to make very few insertions, expand the array by more than one. std::vector typically increases its size by a factor of 1.5.
Sixth, don't increment currentSize until the size changes. That will change all those currentSize-1s into currentSize, which is much less annoying. <g>
Seventh, an array of size N has indices from 0 to N-1, so the top element of the new array is at currentSize - 1, not currentSize.
Eighth, did I mention, you really should use std::vector.
This line is wrong:
memcpy(temparray,values,sizeof values);
The first time this line is run, the values pointer is uninitialized, so it will cause undefined behavior. Additionally, using sizeof values is wrong since that will always give the size of a pointer.
Another issue:
temparray[currentSize] = value;
This will also cause undefined bahavior because you have only allocated currentSize items in temparray, so you can only access indices 0 to currentSize-1.
There is also an error in your array access.
temparray[currentSize/* * (sizeof Comparable) */] = value;
Remember that arrays start at index zero. So for an array of length 1, you would set temparray[0] = value. Since you increment currentSize at the top of the insert function, you will need to do this instead:
temparray[currentSize-1] = value;