-1

I haven't coded in C for at least a year and am trying to brush up on it with writing a very basic software for calibration. Basically I have a PointCloud struct

typedef struct {
    gsl_vector ** vectors;
    gsl_vector * mean;
} PointCloud;

vectors points to an array of gsl_vectors and mean is just a gsl_vector representing the mean of the vectors in vectors.

Now suppose I have a variable PointCloud * foo and assume its internal variables have memory allocated dynamically using malloc() and are populated. Let bar = foo -> vectors. How can I get the number of gsl_vectors in bar (i.e the number of vectors in the point cloud)? I have tried various combinations such as sizeof(bar)/sizeof(bar[0])but that gives me the output 1. sizeof(bar) in itself gives me the value 8. I have tried this on a point cloud with 27 vectors.

WedaPashi
  • 3,561
  • 26
  • 42
Darian H.
  • 1
  • 2
  • 1
    There is no way to determine the number of entries in `vectors` at compile time, which is what calculations involving `sizeof` would require. You must have some way of knowing how many entries are in `vectors`. If you don't then... well, how can you not? – Carey Gregory Jun 25 '15 at 04:00
  • Thanks for that useful info. And yeah don't worry I know how many there are I was just too lazy to give it its own variable in the struct. – Darian H. Jun 25 '15 at 04:03
  • 2
    Then I don't understand your question. – Carey Gregory Jun 25 '15 at 04:09
  • 1
    "I was just too lazy to give it its own variable in the struct." But why not? It's simple, easy and a lot clearer. –  Jun 25 '15 at 04:50
  • You should declare vectors as a pointer to array then, not pointer to pointer, [see this](http://stackoverflow.com/questions/30117161/why-do-i-need-to-use-type-to-point-to-type). – Lundin Jun 25 '15 at 06:19
  • Carey, the was question was basically can I use `sizeof` to determine the number of vectors. That was it. I did not know about the compile time feature of `sizeof`. If I had known I would have stuck with having a size variable and would not have asked the quetion. Like I said, I haven't done C code in a while. Lundin, thank you for your link it was very useful. – Darian H. Jun 25 '15 at 14:13

1 Answers1

0

The sizeof operator is a compile-time operator. When applied to some pointer, it gives the size of pointers on your machine (on my x86-64/Linux system it is 8 bytes), and since it is computed at compile time it does not depend at the run-time size of the dynamically allocated heap memory zone.

You need to keep somewhere the size of any dynamically malloc-ed array or zone. You might consider ending your struct with a flexible array member and keeping its size as a previous member of that struct

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547