I defined a class with a template that defines a generic array type T number of elements N. I have another class that has an instance of this array as a member. When I try using the setString function, the array I pass goes from 15 elements, to 4 elements, arbitrarily.
// testClassArraySize.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <istream>
#include <ostream>
using namespace std;
template<class T, int N>
class CArray {
public:
T arr[N];
CArray(void) {/*arr=(T *)malloc(sizeof(T)*N);*/
if (arr == NULL) {
cout << "allocation error\n";
}
}
;
//CArray (int n) {arr=new T [n]; if(arr==NULL){exit(0); cout<<"allocation error\n";}};
CArray operator=(const T *);
T operator[](const int i) {
return arr[i];
}
;
};
template<class T, int N>
CArray<T, N> CArray<T, N>::operator=(const T *srce) {
size_t x = sizeof(arr);
size_t y = sizeof(srce);
for (int j = 0; j < sizeof(arr); j++) {
if (j > sizeof(srce)) {
arr[j] = 0;
break;
}
arr[j] = srce[j];
}
return *this;
}
class myTestClass {
private:
CArray<char, 15> myString;
public:
myTestClass setString(char set[15]) {
myString = set;
size_t x = sizeof(set);
return *this;
}
;
};
int main() {
myTestClass myObject;
myObject.setString("helloWorld");
return 0;
}
Does anyone have any idea why?
This has a couple of issues, but the one you’ll probably see is the line
Note:
const T* sourceis a pointer, thereforesizeof(srce)is the size of the pointer. I guess you’re using a 32 bit system?sizeofgives you the size of an object (i.e. a “region of storage”). For arrays, that is the size of the whole array in bytes.sizeof( int[10] ) == sizeof(int) * 10. A pointer is itself an object, with a size depending on the C++ implementation (OS, compiler and so on). On 32 bit systems, it typically is 4 byte.sizeof( char* )therefore is 4 byte, not the length of the array you passed to the function, that issizeof( (char*)(char[10]) )still is 4 byte, not 10.Another issue you may see (but only by debugging / tracing) is that
setString(char set[15])is resolved tosetString(char* set). Thereforex = sizeof(set)resolves tox = sizeof(char*)which is typically 4.You pass “helloWorld” to
setString, which is expecting a15-item char arraychar*; I would say this is not a good idea since “helloWorld” has typechar const[10](note theconst).The correct syntax for taking a 15-char array is
char (&set)[15].You can do this more elegantly if you add a template member function like:
This way, you’ll get the array size as a template argument. Note: since I used
const There in the assignment op, you’ll need to enforce const also insetString.