SRL Archive - C/C++ Help and Tutorials

Array size


Bad Boy JH

2011-08-13 01:26:23

I have a uni assignment in C++ which requires me to have a constructor with this method signature:
Train(int arr[]);

it needs to go into a linklist, and so I need to know the size of it. I have no idea how to do it, sizeof() only works in the function the integer was defined in, so I can't use that, so I thought maybe one of you guys could help me.

n3ss3s

2011-08-13 01:31:31

I'm pretty sure sizeof() is for getting the size of the datatype, not the actual value. What is it that's size you are trying to get, exactly?

Bad Boy JH

2011-08-13 01:42:56

the length of the array.

If you declare an integer array of length 3, then size returns 12 (3 * 4 bytes). but if you pass it as a parameter, it will return 4 again.

R0b0t1

2011-08-13 01:57:42

sizeof() works as you would expect on statically defined arrays, that is, it returns the number between the brackets (e.g. "5" in "int arr[5];"). In any other context it returns the number of bytes required to store the given data type - "int arr[];" devolves into a pointer, which is 4 bytes.

As for how to find the length of the array, you either need to explicitly pass it to the function as a separate parameter, or make it an instance variable if this is part of the class. Since it is a constructor, you really have no other option that to pass it separately and remember it in an instance variable.

Bad Boy JH

2011-08-13 02:23:45

I defined it like

int arr = {1, 2, 3};
Train train(arr);

where Train is the class name and train is the variable name (for testing so far only).

since the array has only positive numbers (or 0) as values, would it be worth putting -1 on the end of the array, and then reading values until I see -1?

superuser

2011-08-19 01:20:20

sizeof works in compile time. If you pass the array pointer to a function and ask for sizeof this pointer, you'll get the sizeof the pointer (32/64 bit at least 4 or 8 bytes depending the machine). But if your sizeof call see the actual array declaration (thus they are in the same scope) then the sizeof will not convert the array identifier to a pointer, and returns the array size in bytes.

As you are coding with C++, why not use the standard library instead, like std::vector for these kind of things?