array has no values?
Oct 4, 2017 at 1:21pm UTC
hey guys,
I declared a function that returns a pointer to an array,but when I try to print the values out in main all the values seem to be null or blank
what am I doing wrong?
thanks
1 2 3 4 5 6 7 8 9 10
string* newArray(){
string *ray = new string[4];
for (int i = 0; i < sizeof (ray) / sizeof (string); i++){
ray[i] = ("hello" );
}
return ray;
}
main
1 2 3 4 5 6 7 8 9 10
string* arr = newArray();
for (int i = 0; i < 4; i++){
cout << "array = " << arr[i] << endl;
}
delete [] ray
Oct 4, 2017 at 1:27pm UTC
sizeof (ray)
Ray is a pointer, so probably 4 (or maybe 8). Nothing to do with the size of what ray is pointing to.
sizeof (string)
Who knows. 32 on one test system I tried.
So your code says:
1 2 3 4 5
for (int i = 0; i <4 / 32; i++){
ray[i] = ("hello" );
}
What is 4/32 ? Well, that's an int divided by an int, so it's an int. So zero. So your code says:
1 2 3 4 5
for (int i = 0; i <0; i++){
ray[i] = ("hello" );
}
So you never write anything into the strings.
Oct 4, 2017 at 2:23pm UTC
as pointed out already, sizeof is the wrong thing to use. The "sizeof(ray) / sizeof(string)" C-style trick is for arrays, while what you have there is a pointer. It's important to understand the difference between arrays and pointers, especially if you plan on working with C.
In general, use of pointers and especially use of new and delete is a sign of bad C++ code: this is how the same task could be done today:
1 2 3 4 5 6 7 8 9 10 11
#include <vector>
#include <string>
#include <iostream>
std::vector<std::string> newArray() {
return {4, "hello" };
}
int main() {
auto arr = newArray();
for (auto & s: arr)
std::cout << "array = " << s << '\n' ;
}
live demo:
https://wandbox.org/permlink/iX6SbbKRPHtqhaIJ
Last edited on Oct 4, 2017 at 2:25pm UTC
Oct 4, 2017 at 4:12pm UTC
that makes sense thanks guys
Topic archived. No new replies allowed.