I am having a hard time understanding something essential about character arrays and pointers. I know the subject in itself especially for arrays is confusing as you can only pass arrays to functions using pointers, or return them from functions using pointers, however that is exactly where i have an issue. For my question im going to use an example simple program with 1 private member data and 2 accessor functions.
//NOW IF I DO cout<<vinitlength HERE IT WILL ALWAYS PRINT THE EXACT LEN OF THE
//ARRAY, SO I CAN EASILY SET version=versioninit LIKE SO
for (int i = 0; i < vinitlength; i++) {
version[i] = versioninit[i];
}
}
charbank::~charbank() {}
char* getVersion() {
return version;
}
//LETS PRETEND IM PASSING THIS FUNCTION A VALUE LIKE SO
//char newa[] = "v1.2680"
//mycharbank.setVersion(newa);
void setVersion(char *newv) {
int newvlength;
newvlength = (int) sizeof(newv) / (int) sizeof(newv[0]);
//NOW IF I DO cout << newvlength HERE IT ALWAYS PRINTS OUT 4!! IM ASSUMING
//THIS IS BECAUSE THE POINTER IS 4 BYTES LARGE, BUT HOW CAN I MAKE THIS WORK?
//HERE IS SOME OF THE THINGS IVE TRIED TO GET THE ARRAY AS A LOCAL MEMBER TO
//THIS FUNCTION SO I CAN CALCULATE ITS LENGTH
char test[] = newv //complains about not declaring size
char test[25] = newv //errors incompatible type
char test[] = *newv //Why doesnt this work? am i not dereferencing the ptr?
//I only get 1 digit, i know the ptr is only to the
//first char but come on!
}
I cannot help but reach the conclusion that you cannot directly calculate the length of an array using sizeof if its been passed into a function as a pointer. That also leads me to believe that in this case you are going to have to pass the length of the array the pointer is referring to as a seperate parameter, and coming from java its hard to understand
I cannot help but reach the conclusion that you cannot directly calculate the length of an array using sizeof if its been passed into a function as a pointer. That also leads me to believe that in this case you are going to have to pass the length of the array the pointer is referring to as a seperate parameter, and coming from java its hard to understand
Why's that hard to understand? You clearly understand.
Be sure to take a look at proper C++ strings, which will happily tell you their size, along with other such C++ objects like vector.