Is it best practice to transfer arrays and their variable lengths to a structure in C?

I will soon start using C for a course in operating systems, and I read about the best practices for using C to reduce headaches later.

These were always my first questions regarding arrays, as they are easy to screw in.

Is it common practice to bind an array and its associated variable containing its length in the structure?

I have never seen it in books, and usually they always keep two separate or use something like sizeof (array [] / array [1]).

But by wrapping them in a structure, you can pass the structure both by value and by reference, which you cannot really do with arrays unless you use pointers, in which case you need to track the length of the array again.

I am starting to use C, so the above can be terribly wrong, I'm still a student.

Cheers, Kai.

+5
source share
11 answers

Of course you can do it. Not sure what I would call it best practice, but it is certainly nice to make C fairly rudimentary arrays a bit more manageable. If you need dynamic arrays, it is almost a requirement to group the various fields necessary for bookkeeping together.

Sometimes you have two sizes in this case: one current and one allocated. This is a compromise in which you spend less resources at some speed, paying a little with an excess of memory.

, sizeof , . , , , :

int array[4711];
int i;

for(i = 0; i < sizeof array / sizeof *array; i++)
{
  /* Do stuff with each element. */
}

, sizeof , .

. , , - GArray glib. - , :

typedef struct {
  gchar *data;
  guint len;
} GArray;

, API , , .

+3

, C. .

. , . , , . , , .

+5

.

  • ( ) , sizeof, : sizeof(array)/sizeof(array[0])
  • ( , ),
  • , , . , , , , . . , , , , struct.
+3

API . , ( ) , . . /, , - . , , , . , , . - kvec.

+2

, . , , ++ vector. , ++, , , vector.

+2

, , , , , . C - , .

+1

, . , "" . , , .

+1

, sizeof. struct, , . ( ).

, . , struct, :

struct Foo {
  int *myarray;
  int size;
};

, , , , int ( ) int ( ).

-, . , , , , . , . , .

+1

, , ...:-) , . , , - ... .

0

, ( , # ), sizeof() ( , , "), , , - .

, , -, , , - , . , , .

0
0

All Articles