I know I could use std::vector in C++ instead of arrays and save me some trouble. However this question is not for practical application. Its rather for my understanding. I see '0' instead of the actual value on memcpy() operation. What am I doing wrong in this test code?
#include <stdint.h>
#include <cstring>
#include <cstdlib>
#include <iostream>
using namespace std;
class IntList
{
private:
int* m_anList; //I could use std::vector in practical applications I know
//However I want to experiment what happens
public:
IntList(const int m_anList[]){
this->m_anList = new int[sizeof(m_anList+1)]; //heap allocation - since bad idea to copy on stack
memcpy((int*)this->m_anList,m_anList,sizeof(m_anList+1)); //<-This does not look right
cout << this->m_anList[4] << endl;//<- gives '0'??? Not expected
}
~IntList(){
if(this->m_anList)
{
delete[] this->m_anList;
}
}
int& operator[] (const int& nIndex);
};
int& IntList::operator[] (const int& nIndex)
{
cout << this->m_anList[nIndex] << endl; //<- gives '0'??? Not Expected
return this->m_anList[nIndex];
}
int main()
{
int test_array[10] = {1,2,3,4,5,6,7,8,9};
IntList test(test_array);
test[2];
return 0;
}
I have used it on char* before and it has worked. char = 1 Byte, int = 2 Bytes but memcpy applies to void*.
Updated Code/ Solution (Thanks to Rob (who pointed out my most fundamental of several mistakes) and everyone who replied. I am not CS grad but would try to code better in the future. Thanks again.)
#include <stdint.h>
#include <cstring>
#include <cstdlib>
#include <iostream>
//#include <algorithm>
//#include <vector>
using namespace std;
class IntList
{
private:
int* m_anList; //I could use std::vector in practical applications I know
//However I want to experiment what happens
public:
IntList(const int m_anList[], std::size_t n){
this->m_anList = new int[n * sizeof(int)];
memcpy(this->m_anList,m_anList,n*sizeof(m_anList[0]));
cout << this->m_anList[4] << endl;
}
~IntList(){
if(this->m_anList)
delete[] this->m_anList;
}
int& operator[] (const int& nIndex);
};
int& IntList::operator[] (const int& nIndex)
{
cout << this->m_anList[nIndex] << endl;
return this->m_anList[nIndex];
}
int main()
{
int hello[10] = {1,2,3,4,5,6,7,8,9};
//cout << hello[3] << endl;
IntList test(hello,10);
test[2];
return 0;
}