How to assign a pointer that have been return by a function to a structure array?

Viewed 37

In C code, I'm stuck right here, trying to assign some values to a structure array. I just learned C++ and don't know much on how pointers work. Here is the code as for now:

typedef struct Weather {
    float temperature;
    float wind;
    float humidity;
    float precipitation;
} Weather;

const int NUMDATA = 1440;
Weather weather[NUMDATA];



float* generateRandom(float max, float min) {

    static float array[NUMDATA];
    
    for (int i=0; i<NUMDATA; i++) {
        array[i] = rand() / (float) RAND_MAX * (max - min) + min;
    }    
    
    return array;
}


void readWeather() {
    
    weather.temperature = generateRandom(40,20);
    weather.wind = generateRandom(20,0);
    weather.humidity = generateRandom(100,0);
    weather.precipitation = generateRandom(20,0);
    
}

I just run the readWeather() function in the main function and it outputs an error for each line in readWeather() saying that

main.cpp:44:13: error: request for member ‘wind’ in ‘weather’, which is of non-class type ‘Weather [1440]

1 Answers

Since you're manipulating arrays, not single elements, you need to somehow loop over them to do the assignment. You might do a for loop:

float* rnd = generateRandom(40, 20);
for (int i = 0; i < NUMDATA; ++i) {
    weather[i].temperature = rnd[i];
}
rnd = generateRandom(20, 0);
for (int i = 0; i < NUMDATA; ++i) {
    weather[i].wind = rnd[i];
}
// etc.

You might also use std::memcpy() as these are POD types (float types). However, to make it cleaner, it's better to use std::array<>, and/or to pass the reference to the array to be filled instead of returning a pointer to a function-local static. That'd look like this:

void generateRandom(float* array, float max, float min, size_t numData = NUMDATA) { 
    for (int i=0; i<numData; i++) {
        array[i] = rand() / (float) RAND_MAX * (max - min) + min;
    }
}

void readWeather() {
    for (int i = 0; i < NUMDATA; ++i) {
        generateRandom(weather[i].temperature, 40, 20);
        generateRandom(weather[i].wind, 20, 0);
        // ...
    }
}
Related