Reputation:
I am working on a coding assignment for my class and I ran into a problem!
I have this constructor here, for a String object:
String::String(char str[]) {
size = (sizeof(str)/sizeof(str[0]));
data = new char[size];
for (int i = 0; i < size; ++i) {
data[i] = str[i];
}
}
Here is part of the main I was provided:
char test[11] = "Hello world";
String two(test);
cout << "The length of String two is: " <<
two.length() << endl;
cout << "The value of String two is: ";
two.print();
So when I run this, I would get 8 for the size (should be 11). However, after some research, I figured out it is because the sizeof(str) is returning the byte size of a pointer, rather than the entire array.
So is there any way to get the size of the whole array with what I have? I am not supposed to manipulate the provided main, therefore I cannot add an int size to the parameters, which would be the obvious solution.
I've been stuck on this one for a bit, thanks for any help and suggestions,
Upvotes: 0
Views: 1486
Reputation: 62777
You can not get size of array at runtime in C. At runtime, array is just the address. The size is simply not stored anywhere. In source code, at compile time, in a place where compiler knows the size, you can use sizeof
operator, but that gets essentially converted to a constant numeric literal, ie. same as writing the right number there yourself (VLAs are a bit more complex case, and of course using sizeof
can create portable code unlike hard-coded number).
To make matters worse (for understanding C), when you have a function parameter that looks like an array, it really is a pointer. Even if you give it static size in the parameter list, sizeof
still it gives you size of pointer, for example. Only non-parameter variables can actually be arrays, with sizeof
working as expected.
You have to pass the size somehow (usually as extra parameter) or have some other way of telling where the data ends (such as strings' '\0'
at the end).
Upvotes: 1
Reputation: 7374
Array decays to pointer when passed to a function.
You have to either pass the length to the function, pass a STL container e.g. std::vector
or use strlen()
inside function. (Note that strlen()
need a terminating null-character to work properly and you have to add that to your array)
Upvotes: 4
Reputation: 21
Use a vector instead of char array. You can get size by calling size() method of vector container. If you want to use a char array, then it is a common practice in c programming to pass size as second parameter in the function.
You will only get size of array using sizeof() function on the function stack in which the array is defined and if the array size is known in compile time.
Upvotes: 0