My assignment is to make a ragged array. In order to allocate memory for rows, I need to take the first integer from first row and allocate. That's the easy part. However, in order to allocate memory for the remaining rows, I need to first get the number of elements for each row. The problem is that each row does not have the exact number of elements.
I can do the rest of the assignment (calculating the mean and sorting).
Please show me how to do bold portion of this assignment.
//Take this example with a grain of salt; I am not very knowledgeable with C
constint rows(10);
constint columns(15);
float* f_ptr = malloc(rows*columns);
//Initialize values
for(int I=0; I < rows*columns; ++I){
*(f_ptr + I) = 0;
}
//...Retrieve info from file...
for(int I = 0; I < rows*columns; ++I){
if(
((f_ptr + I) != 0) &&
(*(f_ptr+I) != 0)
)
//...do something
}
//...
free(f_ptr);
As it was already said you can use either a vector of vectors, or an array of vectors. The problem with an array of dynamically allocated arrays for rows is that you should keep sizes of rows in an additional separate array
To read a row you should use std::getline and then use std::istringstream to extract numbers.
I need to first get the number of elements for each row.
Well, you're going to have to count them, then.
Read the file line into a char buffer, count the values on the row, and then convert and store them.
I can see that there are only 42 value which is bigger than the value of 53 you are given on the first line. And you don't even know how may rows you're expecting, so you can only allocate a linear array up front.
I assume you've been learning the (C !) techniques required to solve your problem. I take it you are planning to write (or by now, using) functions to manage access to your ragged array.